import httplib ImportError: No module named httplib - python

I got this error when run test.py
C:\Python32>python.exe test.py
Traceback (most recent call last):
File "test.py", line 5, in <module>
import httplib
ImportError: No module named httplib
How to correct it?
Code block for test.py:
#!/usr/local/bin/python
import httplib
import sys
import re
from HTMLParser import HTMLParser
class miniHTMLParser( HTMLParser ):
viewedQueue = []
instQueue = []
def get_next_link( self ):
if self.instQueue == []:
return ''
else:
return self.instQueue.pop(0)
def gethtmlfile( self, site, page ):
try:
httpconn = httplib.HTTPConnection(site)
httpconn.request("GET", page)
resp = httpconn.getresponse()
resppage = resp.read()
except:
resppage = ""
return resppage
def handle_starttag( self, tag, attrs ):
if tag == 'a':
newstr = str(attrs[0][1])
if re.search('http', newstr) == None:
if re.search('mailto', newstr) == None:
if re.search('htm', newstr) != None:
if (newstr in self.viewedQueue) == False:
print (" adding", newstr)
self.instQueue.append( newstr )
self.viewedQueue.append( newstr )
else:
print (" ignoring", newstr)
else:
print (" ignoring", newstr)
else:
print (" ignoring", newstr)
def main():
if sys.argv[1] == '':
print ("usage is ./minispider.py site link")
sys.exit(2)
mySpider = miniHTMLParser()
link = sys.argv[2]
while link != '':
print ("\nChecking link ", link)
# Get the file from the site and link
retfile = mySpider.gethtmlfile( sys.argv[1], link )
# Feed the file into the HTML parser
mySpider.feed(retfile)
# Search the retfile here
# Get the next link in level traversal order
link = mySpider.get_next_link()
mySpider.close()
print ("\ndone\n")
if __name__ == "__main__":
main()

You are running Python 2 code on Python 3. In Python 3, the module has been renamed to http.client.
You could try to run the 2to3 tool on your code, and try to have it translated automatically. References to httplib will automatically be rewritten to use http.client instead.

you can just import http.client and rename it to httplib with this code :
import http.client as httplib

If you use PyCharm, please change you 'Project Interpreter' to '2.7.x'

I had this issue when I was trying to make my Docker container smaller. It was because I'd installed Python 2.7 with:
apt-get install -y --no-install-recommends python
And I should not have included the --no-install-recommends flag:
apt-get install -y python

Related

Import requests ModuleNotFoundError: No module named 'requests'

I need to run this code but I find this error:
Traceback (most recent call last):
File "C:\Users\DELL\Downloads\snapArt.py", line 1, in <module>
import requests
ModuleNotFoundError: No module named 'requests'
Code:
import requests
from hashlib import sha256
from time import time, sleep
print("""
""")
FielUser = open('Users.txt' , 'r').read().splitlines()
req = requests.session()
def token():
for i, c in enumerate("0001110111101110001111010101111011010001001110011000110001000110"):
if c == "0":
yield sha256(("iEk21fuwZApXlz93750dmW22pw389dPwOk"+"m198sOkJEn37DjqZ32lpRu76xmw288xSQ9").encode('utf-8')).hexdigest()[i]
else:
yield sha256((str(int(round(time() * 1000.0))) + "iEk21fuwZApXlz93750dmW22pw389dPwOk").encode('utf-8')).hexdigest()[i]
for user in FielUser:
if user:
user = user.strip()
url = 'https://app.snapchat.com/loq/suggest_username_v2'
headers = {'User-Agent':'Snapchat/10.25.0.0 (Agile_Client_Error; Android 5.1.1#500181103#22; gzip)'}
data = {
'req_token': "".join(list(token())),
'requested_username': user,
'timestamp': int(round(time() * 1000.0)),
'status_code': ''
}
res = req.post(url, headers=headers, data=data)
if res:
JSON = res.json()
#print(JSON)
if JSON.get('requested_username') and JSON.get('status_code') == 'OK':
with open('Found.txt', "a+") as file_save:
file_save.write(user + '\n')
print('available ->', user)
sleep(1)
else:
print('not available ->', user)
sleep(1)
print('''
''')
Be sure you are not in a virtual environment (venv). This could be one of your issues.
You would not have installed the module called requests. To do that simply open your cmd (command prompt) or terminal and type pip install requests.

ModuleNotFoundError: No module named 'pyzabbix'

pyzabbix is a module needed for this script to work. I installed it using pip, please see a confirmation below:
WARNING: The script chardetect.exe is installed in 'C:\Users\Christopher Ezimoha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\Scripts' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed certifi-2019.11.28 chardet-3.0.4 idna-2.8 pyzabbix-0.7.5 requests-2.22.0 urllib3-1.25.8
C:\Users\Christopher Ezimoha\Desktop>
However, I'm getting an error at line 24 that the module can't be found. I'm not sure what I need to do.
Please see the script below and advise accordingly as I need this code to read a CSV file and update an application called Zabbix.
def addHosts(zapi):
# Add Hosts
file = open('hosts.csv', 'r')
reader = csv.reader(file)
devicelist = list(reader)
import csv
def login():
# Login/authenticate below
session = ZabbixAPI('https://zabbix.xxxxxx.xxx')
# session = ZabbixAPI('http://xxxxxxxxxx/zabbix')
session.login(user="xxxxxxxxxxxx", password="xxxxxxxx")
print("Connected to Zabbix API Version %s" % session.api_version())
return session
for row in devicelist:
device = row[0]
hostgroup = row[1]
responsegroup = zapi.hostgroup.get(filter={'name': hostgroup})
groupid = responsegroup[0]['groupid']
ip = row[2]
templatePriority = row[3]
responsepriority = zapi.template.get(filter={'name': templatePriority})
templatePriorityId = responsepriority[0]['templateid']
# if templatePriority == 'P1':
# templatePriorityId = '40874'
templateType = row[4]
responsetype = zapi.template.get(filter={'name': templateType})
templateTypeId = responsetype[0]['templateid']
try:
response = zapi.host.create(
host=device,
interfaces=[{
'type': 2,
'main': 1,
'ip': ip,
'dns': '',
'port': 161,
'useip': 1
}],
groups=[{
'groupid': groupid}],
templates=[{'templateid': templatePriorityId}, {'templateid': templateTypeId}],
inventory_mode=1
)
print("Created new host: " + device)
except ZabbixAPIException as e:
if 'already exists' in e[0]:
print("Already created host " + device)
else:
print(e[0])
return
def main():
# hostgroup = raw_input('Hostgroup: ')
#hostgroup = "ALTC - Altcar"
zapi = login()
addHosts(zapi)
return
if __name__ == '__main__':
main()
Do you have both python 2 and 3 installed? If you have both, pip installs modules under python2. Try installing like this if you'd like the module to be installed under python3:
pip3 install pyzabbix
There is no import, in the code you included in the question:
from pyzabbix import ZabbixAPI
The login() function should be defined outside of addHosts(), in order to be called like that in main()

Python os.system(python "program") not working

I'm writing a program with multiple pieces of code, and don't want someone to have to manually copy-paste the entire directory from an install disk, so I've written something that will do it for them (like an autorun).
However, when I try to launch the program after copying it over to the user's computer, I get:
Process finished with exit code 0
instead of the installer booting the program.
This is the def I'm using:
import os
get_project_base_directory()
check_version()
print jason_dir
new_dir = str(jason_dir+"/Jason_Core/Boot.py")
command = "python " + new_dir
print command
os.system(command)
Why might os.system might not be working? I've also tried popopen and subprocess, but the had the same output (exit code 0).
EDIT: I am running this in a script, not the python command line.
EDIT 2: As requested, Boot.py:
# 3rd party libraries
import os
import subprocess
import shutil
from imp import find_module
# My code to import
basedir = ""
# Get the project base directory (drive located on)
def get_project_base_directory():
global basedir
cwd = os.getcwd()
basedir = "/".join(cwd.split("\\")[:len(cwd.split("\\"))-1])
#print basedir
# Copies libraries from disk drive
def copy_libs():
new_dir = "c:/Downloads/Python_Libraries"
if os.path.exists(new_dir):
shutil.rmtree(new_dir)
old_dir = basedir + "/Libraries/Installed"
#print old_dir
try:
shutil.copytree(old_dir, new_dir)
except:
print " Error copying directories! Try manual copy."
print " Go to:", basedir + "/Libraries/Installed"
# Checks to see if the library is installed
def check_lib_install():
temp_var = True
libs_list = ("fbchat", "gtts", "pyaudio", "googlevoice", "espeak", "pywapi", "speech_recognition", "win10toast") # names of libs
for lib in libs_list:
print "Checking lib installation:", lib
try:
__import__(lib)
print " Lib installed"
print ""
except:
print " Lib not installed"
install_lib(lib, libs_list.index(lib))
print "All libraires installed!"
# Install libraries if they don't exist on this machine.
def install_lib(lib, index):
print " Installing lib:", lib
libs_file_list = ("/fbchat-1.0.19/", "/gTTS-1.2.2/", "/PyAudio-0.2.11/", "/pygooglevoice-master/", "/python-espeak-0.5/", "/pywapi-0.3.8/", "/speech_recognition-master/", "/Windows-10-Toast-Notifications-master/") # path to file
print "Installing:", lib
new_dir = "c:/Downloads/Python_Libraries" + libs_file_list[index]
os.chdir(new_dir)
try:
temp_command = "python setup.py install"
subprocess.call(temp_command)
except:
print lib, "failed installation. Try manual install."
print ""
# Gets version number of local copy of Jason, and then the version number of the one on the disk drive. If the local version is lower, the python files are overwritten. If it doesn't yet exist locally, Jason is installed.
def check_version():
local_version = "0"
jason_dir = "C:/Jason_AI" # Where is jason installed to?
if os.path.exists(jason_dir):
with open(jason_dir+"\System Files\Version Number.txt") as local_jason: # Where is jason installed to?
counter = 0
for line in local_jason:
counter += 1
if counter == 2:
local_version = line
#print local_version
elif counter == 3:
break
install_version_file = basedir + "\System Files\Version Number.txt"
install_version_file = "/".join(install_version_file.split("\\"))
with open(install_version_file) as drive_jason:
counter = 0
for line in drive_jason:
counter += 1
if counter == 2:
install_version = line
#print install_version
if install_version == local_version:
print "Version up to date!"
print "Using version number:", local_version
else:
shutil.rmtree(jason_dir)
print "Version outdated"
print "Using version number:", local_version
elif counter == 3:
break
else:
print "Version outdated"
print "Using version number:", local_version
# Controls the boot process, when done, launches into Listen.get_audio()
def control():
get_project_base_directory()
copy_libs()
check_lib_install()
import System_Logins # Importing this here since the required libraries might not be installed if its the first time running Jason on this machine
import Actions # ^^
import System_Commands # ^^
import Listen # ^^
check_version()
logins = System_Logins.read_logins(basedir)
System_Commands.clear_screen()
while True:
speech = Listen.get_audio()
Actions.sort(speech, logins)
def check_packages():
packages = ["System_Logins", "Actions", "System_Commands", "Listen"]
for package in packages:
try:
__import__(package) #Need to work on
print package + ":", "successfully loaded."
packages[packages.index(package)] = "True"
except ImportError:
print package + ":", "error."
return packages
#Remote login (ie, from install)
def remote_control():
packages = check_packages()
#print packages
if any(word in ("System_Logins", "Actions", "System_Commands", "Listen") for word in packages):
control()
import System_Logins # Importing this here since the required libraries might not be installed if its the first time running Jason on this machine
import Actions # ^^
import System_Commands # ^^
import Listen # ^^
logins = System_Logins.read_logins(basedir)
System_Commands.clear_screen()
while True:
speech = Listen.get_audio()
Actions.sort(speech, logins)
remote_control()

No requests module error

I'm trying to write a web parser script using requests module. Here is my current code:
import requests
import subprocess
import json
import sys
import threading
import time
from Queue import Queue
numberOfViewers = int(sys.argv[1])
builderThreads = int(sys.argv[2])
startTime = time.time()
numberOfSockets = 0
concurrent = 25
urls = []
urlsUsed = []
def getURL(): # Get tokens
output = subprocess.Popen(["livestreamer", "twitch.tv/CHANNEL_NAME", "-j"],
stdout=subprocess.PIPE).communicate()[0]
return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter
def build(): # Builds a set of tokens, aka viewers
global numberOfSockets
global numberOfViewers
while True:
if numberOfSockets < numberOfViewers:
numberOfSockets += 1
print ("Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers))
urls.append(getURL())
def view(): # Opens connections to send views
global numberOfSockets
while True:
url=q.get()
requests.head(url)
if (url in urlsUsed):
urls.remove(url)
urlsUsed.remove(url)
numberOfSockets -= 1
else:
urlsUsed.append(url)
q.task_done()
if __name__ == '__main__':
for i in range(0, builderThreads):
threading.Thread(target = build).start()
while True:
while (numberOfViewers != numberOfSockets): # Wait until sockets are built
time.sleep(1)
q=Queue(concurrent*2)
for i in range(concurrent):
try:
t=threading.Thread(target=view)
t.daemon=True
t.start()
except:
print ('thread error')
try:
for url in urls:
print (url)
q.put(url.strip())
q.join()
except KeyboardInterrupt:
sys.exit(1)
But when I run the code, it says:
Traceback (most recent call last):
File "C:\Users\flamelier\Desktop\Twitch.py", line 1, in <module>
import requests
ImportError: No module named 'requests'
Why am I getting this error? How do I install this module?
Will this error keep repeating for all the scripts henceforth?
How can I prevent such similar errors in the future?
Requests is a 3rd party module. You should first install it to Python using PIP or easy_install.
You have to run pip3 install requests as requests doesn't come with Python by default, as it is a third party library.
Even after you have pip3-installed requests, the code shown won't do anything. The
if __name__ == "__main__"
test and everything after it is part of an else block in the view function. Back this line and the block that follows out to the left margin.

unittest - Importerror

I'm following this tutorial on web2py where you get to make a testdriven environment. However when I try to run the test with unittest, selenium I get this error:
$ python functional_tests.py
running tests
Traceback (most recent call last):
File "functional_tests.py", line 56, in <module>
run_functional_tests()
File "functional_tests.py", line 46, in run_functional_tests
tests = unittest.defaultTestLoader.discover('fts')
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 202, in discover
raise ImportError('Start directory is not importable: %r' % start_dir)
ImportError: Start directory is not importable: 'fts'
This is how the functional_tests.py looks like:
#!/usr/bin/env python
try: import unittest2 as unittest #for Python <= 2.6
except: import unittest
import sys, urllib2
sys.path.append('./fts/lib')
from selenium import webdriver
import subprocess
import sys
import os.path
ROOT = 'http://localhost:8001'
class FunctionalTest(unittest.TestCase):
#classmethod
def setUpClass(self):
self.web2py = start_web2py_server()
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(1)
#classmethod
def tearDownClass(self):
self.browser.close()
self.web2py.kill()
def get_response_code(self, url):
"""Returns the response code of the given url
url the url to check for
return the response code of the given url
"""
handler = urllib2.urlopen(url)
return handler.getcode()
def start_web2py_server():
#noreload ensures single process
print os.path.curdir
return subprocess.Popen([
'python', '../../web2py.py', 'runserver', '-a "passwd"', '-p 8001'
])
def run_functional_tests(pattern=None):
print 'running tests'
if pattern is None:
tests = unittest.defaultTestLoader.discover('fts')
else:
pattern_with_globs = '*%s*' % (pattern,)
tests = unittest.defaultTestLoader.discover('fts', pattern=pattern_with_globs)
runner = unittest.TextTestRunner()
runner.run(tests)
if __name__ == '__main__':
if len(sys.argv) == 1:
run_functional_tests()
else:
run_functional_tests(pattern=sys.argv[1])
I solved this problem by replacing fts with the full path i.e. /home/simon/web2py/applications/testapp/fts
Hope this helps
I had the same problem and based on an excellent article unit testing with web2py,
I got this to work by doing the following:
Create a tests folder in the tukker directory
Copy/save the amended code(below) into tests folder as alt_functional_tests.py
Alter the web2py path in the start_web2py_server function to your own path
To run, enter the command: python web2py.py -S tukker -M -R applications/tukker/tests/alt_functional_tests.py
I am no expert but hopefully this will work for you also.
import unittest
from selenium import webdriver
import subprocess
import urllib2
execfile("applications/tukker/controllers/default.py", globals())
ROOT = 'http://localhost:8001'
def start_web2py_server():
return subprocess.Popen([
'python', '/home/alan/web2py/web2py/web2py.py', 'runserver',
'-a "passwd"', '-p 8001' ])
class FunctionalTest(unittest.TestCase):
#classmethod
def setUpClass(self):
self.web2py = start_web2py_server()
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(1)
#classmethod
def tearDownClass(self):
self.browser.close()
self.web2py.kill()
def get_response_code(self, url):
"""Returns the response code of the given url
url the url to check for
return the response code of the given url
"""
handler = urllib2.urlopen(url)
return handler.getcode()
def test_can_view_home_page(self):
# John opens his browser and goes to the home-page of the tukker app
self.browser.get(ROOT + '/tukker/')
# He's looking at homepage and sees Heading "Messages With 300 Chars"
body = self.browser.find_element_by_tag_name('body')
self.assertIn('Messages With 300 Chars', body.text)
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(FunctionalTest))
unittest.TextTestRunner(verbosity=2).run(suite)
First you have to do some changes in wrong paths in fts/functional_tests.py
search for
'python', '../../web2py.py', 'runserver', '-a "passwd"', '-p 8001'
and change it to
'python', '../../../web2py.py', 'runserver', '-a "passwd"', '-p 8001'
then
tests = unittest.defaultTestLoader.discover('fts')
to
tests = unittest.defaultTestLoader.discover('.')
then
tests = unittest.defaultTestLoader.discover('fts', pattern=pattern_with_globs)
to
tests = unittest.defaultTestLoader.discover('.', pattern=pattern_with_globs)
and
sys.path.append('fts/lib')
to
sys.path.append('./lib')

Categories

Resources