c++ embed python urllib - python

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.

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)");
...

Related

Selenium Helper No Module

Traceback (most recent call last):
File "gen.py", line 9, in <module>
from SeleniumHelper import SeleniumHelper
ImportError: No module named 'SeleniumHelper'
# python accounts.py -i ../../data/twitter-creator.json -d regular -f 1
# python accounts.py -i ../../data/twitter-creator.json -d proxy -f 1
import sys
import time
import getopt
import simplejson
from selenium import webdriver
from seleniumHelper import seleniumHelper
class TwitterCreator(SeleniumHelper):
MOBILE_URL_CREATE = 'https://mobile.twitter.com/signup?type=email'
MOBILE_FIELD_SIGN_UP_NAME = '#oauth_signup_client_fullname'
MOBILE_FIELD_SIGN_UP_EMAIL = '#oauth_signup_client_phone_number'
MOBILE_FIELD_SIGN_UP_PASSWORD = '#password'
MOBILE_FIELD_SIGN_UP_USERNAME = '#custom_name'
MOBILE_BUTTON_SKIP_PHONE = '.signup-skip input'
MOBILE_BUTTON_INTERESTS = 'input[data-testid="Button"]'
DESKTOP_URL_CREATE = 'https://twitter.com/signup'
DESKTOP_URL_SKIP = 'https://twitter.com/account/add_username'
DESKTOP_URL_MAIN = 'https://twitter.com'
import mechanize
import cookielib
import subprocess
dear python masters. I am getting selenium helper error. I posted the error above. I tried hard to decode the code. but I couldn't find where is the error. where is the problem? I will be very happy if you answer. good work.
note:there is also another file called selenium. I put the error code at the top.
note2: I installed selenium with pip. but he doesn't see.
from SeleniumHelper import SeleniumHelper
--this is improper syntax. Ostensibly you could do import SeleniumHelper as SeleniumHelper? I'm not sure how this differs from simply import SeleniumHelper anyway.

Communicating from node to python using json gives me error

I'm trying to communicate to python from node using PythonShell. When I set the mode to json, I get an error
WARNING: Logging before flag parsing goes to stderr.
^
SyntaxError: Unexpected token W in JSON at position 0
My python file so far contains the following
import json
import random
import tensorflow
import tflearn
import numpy
import sys
import pickle
import nltk
from nltk.stem.lancaster import LancasterStemmer
stemmer = LancasterStemmer()
nltk.download('punkt')
This is how I'm calling the python file from node:
const options = {
mode: 'json',
pythonOptions: ['-u'],
pythonPath: 'python'
};
let pyshell = new PythonShell('./python/script.py', options);
pyshell.on('message', async function(message) {
autoResponseHandler(message);
});
What am I doing wrong, and how can I set the mode to json correctly?
Answer:
In your python script, you need to return a message of the json-form '{ ex: "something"}'.
I suspect you're attempting to pass a plain string as the message to pyshell.on(). Before you pass 'message', you need to convert it to JSON format.
So when I run the following code:
import json
import random
import tensorflow
import tflearn
import numpy
import sys
import pickle
import nltk
from nltk.stem.lancaster import LancasterStemmer
stemmer = LancasterStemmer()
message = nltk.download('punkt')
print(message)
The output is 'true'... What is your intention here?

Why does import urllib fail if import matplotlib is absent?

I'm running python 3.4 under Win7.
Why does 'import urllib' fail if 'import matplotlib' is absent?
import urllib
import socket
import sys, os
import matplotlib.pyplot # urllib won't work unless this is here ! WTF?? !
url='https://finance.yahoo.com/quote/SPY/history?period1=1410652800&period2=1536883200&interval=1d'
bytes = urllib.request.urlopen(url, timeout=4).read()
page = str( bytes, encoding='utf8' )
print("Page length="+str(len(page)))
sys.exit
Without import matplotlib.pyplot, program fails with this error:
File "C:\Python34\minibigdrops.py", line 8, in module
bytes = urllib.request.urlopen(url, timeout=4).read()
AttributeError: 'module' object has no attribute 'request'
The other attributes, like 'error', aren't found either.
I see that several others have posted problems with urllib. Perhaps they could try also importing matplotlib.

Script doesn't work on Linux

I made a small discord bot in python. On windows it works perfectly fine, but when I try to run it on raspbain, it says invalid syntax (with the command "python3 Bot.py")
Here's the code:
import feedparser
from yaml import load, dump
from json import dumps as jdump
from requests import post
import xml.etree.ElementTree as ET
BASE_URL = "https://discordapp.com/api"
def get_from_summary(summary):
root = ET.fromstring(f"<element>{summary}</element>")
d = f"{root[1].text}\n\n{root[2].text}"
i = root[0].attrib["src"]
return (d, i)
The syntax is at root = ET.fromstring(f"<element>{summary}</element>") with the "
The code uses formatted string literals (the f"<element>{summary}</element>"), which were only introduced in Python 3.6, so you need to use at least that version of Python.

Python printing a string yields an unexpected result

Trying to print / work with a specific String is driving me crazy in Python - or to specify this: I am using Jython.
The simple command
print "appilog.xxxxx.xxxxx.xxxxxxx"
results in a print of something looking like a java package
com.xxxxx.xxxxx.xxxxxx
Does Python/Jython do any special lookup for strings? Is there a way to enforce the usage of the "original" string I entered before?
Other things I tried are the following:
print ("appilog...")
print r"appilog..."
print str("appilog...")
print str(r"appilog...")
Imports used in the script this command is located in are the following:
from com.hp.ucmdb.discovery.probe.services.dynamic.core import EnvironmentInformation
#coding=utf-8
import string
import re
import sys
import os
import ConfigParser
import shutil
import StringIO
import logger
import modeling
import time
import subprocess
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import datetime
from appilog.common.system.types.vectors import ObjectStateHolderVector

Categories