Why does import urllib fail if import matplotlib is absent? - python

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.

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.

ValueError: source code string cannot contain null bytes mysql.connector

I have somehow encountered a null byte into my code and i am getting this error:
File "py.py", line 7, in <module>
import mysql.connector
ValueError: source code string cannot contain null bytes
This is the code which is producing error:
from time import sleep
import sys
import requests, json
from datetime import datetime as dt
from datetime import timedelta
import threading
import mysql.connector
print('ok')
However, removing the line 'import mysql.connector' the program works just fine?
any suggestions?
I tried removing the error by using this answer but it did not work?
any suggestions?
I tried to reinstall the mysql-connector-python library. It worked just fine :/

Python cannot import from another file name not defined

I am trying to import a custom function from another python file but keep getting an error NameError: name 'testme' is not defined. I confirmed that I am importing the file correctly according to this SO post and that the function is top level. What else can I try to fix this?
My main python file is:
import sys
import dbconn
#from dbconn import testme #<----did not work
dev=True
if(dev):
categId='528'
pollIds=[529,530,531]
else:
categId=str(sys.argv[1])
pollIds=[529,530,531]
df=testme(categIds)#callServer(categId,pollIds)
df
if(not categId.isdigit):
print('categ id fail. expected digit got: '+categId)
.....
and dbconn.py:
import pymysql #pip3 install PyMySQL
import pandas as pd
from scipy.stats.stats import pearsonr
from scipy import stats
def testme(categIds):
try:
df=categIds
except Exception as e:
print("broke")
return categIds
Not sure if it makes a difference but I am running the main python file from within a Jupyter notebook, and have a compiled version of dbconn.py in the same directory
In response to the suggestions I tried:
df=dbconn.testme(categIds)
got the error:
module 'dbconn' has no attribute 'testme'
You Have to follow these fox exact import
1)import <package>
2)import <module>
3)from <package> import <module or subpackage or object>
4)from <module> import <object>
in your case, you have tried
from dbconn import testme
you have to use only packages in from section and module in import section
like >>
from testme import dbconn

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

Using BeautifulSoup in CGI without installing

I am trying to build a simple scraper in Python, which will run on a Webserver via CGI. Basically it will return a value determined by a parameter passed to it in a URL. I need BeautifulSoup to do the processing of HTML pages on the webserver. However, I'm using HelioHost, which doesn't give me shell access or pip etc. I can only use FTP. One the BS website, it says you can directly extract it and use it without installing.
So I got the tarball on my Win7 machine, used 7-zip to remove bz2 compression, and then tar compression, which gave me a bs4 folder and a setup.py file. I transferred the complete bs4 folder to my cgi-bin directory where the python script is located via ftp. My script code is :
#!/usr/bin/python
import cgitb
cgitb.enable()
import urllib
import urllib2
from bs4 import *
print "Content-type: text/html\n\n"
print "<html><head><title>CGI Demo</title></head>"
print "<h1>Hello World</h1>"
print "</html>"
But it is giving me an error:
/home/poiasd/public_html/cgi-bin/lel.py
6 import urllib
7 import urllib2
8 from bs4 import *
9
10 print "Content-type: text/html\n\n"
bs4 undefined
SyntaxError: invalid syntax (__init__.py, line 29)
args = ('invalid syntax', ('/home/poiasd/public_html/cgi-bin/bs4/__init__.py', 29, 6, 'from .builder import builder_registry\n'))
filename = '/home/poiasd/public_html/cgi-bin/bs4/__init__.py'
lineno = 29
msg = 'invalid syntax'
offset = 6
print_file_and_line = None
text = 'from .builder import builder_registry\n'
How can I use the bs4 module via CGI? How can I install but not-install it? Can I convert the BeautifulSoup I have on my PC to a nice little BeautifulSoup4.py which will contain all the code?
You are using a version of Python that doesn't yet support PEP 328 Relative Imports; e.g. Python 2.4 or older. BeautifulSoup 4 requires Python 2.7 or newer.
Presumably you cannot upgrade to a newer Python version. In that case you can try using BeautifulSoup 3; it'll have a few bugs and you'll be missing some features, but at least you can get past the syntax error.
However, I note that HelioHost does list Python 2.7 as supported.

Categories