Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ embed python urllib

python 2.7.10(./Watcher/epMain.py):

import subprocess
import hashlib
import os
import sys
import zipfile
import httplib
#import urllib 
#import urllib2

def letsbegin():
    subprocess.call('a.exe')
    httpClient = httplib.HTTPConnection('www.google.com', 80, timeout=30)
    httpClient.request('GET', '/updata/Client_V.html')
    response = httpClient.getresponse()
    targetV = response.read()
letsbegin()

c++:

Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./Watcher')");
PyObject *pyMain = PyImport_ImportModule("epMain")

The pyMain is always NULL but after I change my python code to:

 import subprocess
 import hashlib
 import os
 import sys
 import zipfile
 #import httplib
 #import urllib 
 #import urllib2

def letsbegin():
    subprocess.call('a.exe')
    httpClient = httplib.HTTPConnection('www.google.com', 80, timeout=30)
    httpClient.request('GET', '/updata/Client_V.html')
    response = httpClient.getresponse()
    targetV = response.read()
letsbegin()

then it is ok to load this module in my c++ code but I really want to use httplib in this project,How? I can't use:

PyImport_ImportModule("httplib")

because python code may update often. besides,when I use

d:\pros\go\Watcher>python epMain.py

it works!
urllib and urllib2 also have problems like this.

like image 939
rookie Avatar asked Feb 26 '26 08:02

rookie


1 Answers

It seems like you compile with Python 3.x include/libs instead of 2.x.

In Python 3.x, httplib, urllib2 is not available. (They are renamed to http.client' andurllib.request,urllib.error`)

Change compile option to include, link with Python 2.x.

UPDATE

To check which version the C++ program using, try the following code:

Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("print(sys.version)");
...
like image 183
falsetru Avatar answered Feb 28 '26 21:02

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!