I am currently running Python 3.8.0.
I have a program but when executing it, I am getting a ModuleNotFoundError and it points to 'urllib2'
I've tried to fix this issue as this seems to be a common thing, but cannot figure out where I am getting stuck. Any help would be appreciated. Below are the errors and the Python code.
#!/usr/bin/env python
from __future__ import print_function
from urllib.request import urlopen
import json
def main():
ip = json.loads(urlopen('https://ifconfig.co/json').read())['ip']
print(json.dumps({'ip': ip + '/32'}))
if __name__ == '__main__':
main()
Related
I am trying to make use of the streamlit SessionState, when I import SessionState. I get the following error: ModuleNotFoundError: No module named 'SessionState'
when using he SessionState
Here is a snipnet of my code:
from multiprocessing import Process
import streamlit as st
import SessionState
import time
import os
import signal
st.sidebar.title("Controls")
start = st.sidebar.button("Start")
stop = st.sidebar.button("Stop")
state = SessionState.get(pid=None)
Has anyone encountered this and how did you fix it? There are no resources online
https://docs.streamlit.io/en/stable/changelog.html?highlight=SessionState#version-0-54-0
Seems like you have to download this gist and put it into your project in order to use SessionState
Chaps I am going through what is apparently a #1 problem for python novice. I have been through some tutorials but I really can t get it works. Here is the code :
import time
from settings import *
from actif_class import *
from get_settings import *
from dataython import *
from spreadython import *
from tankython import *
if __name__ == "__main__":
t0 = time.clock()
settings = get_settings()
tickers = get_data_mp(settings)
list_spreads = get_list_spread(tickers,settings)
list_spreads_tank = tanking(list_spreads,settings)
spread_traitable = obtention_spreads_traitables(list_spreads_tank,settings)
print 'done. Timing',time.clock()-t0,'seconds'
and here is the stack :
ImportError: No module named datayhton
Even though the module DOES exist and is in the same folder as every other modules. It is able to see the get_settings one but not dataython. I ve tried on another machine but still got the same trouble.
I tried to go through import sys, sys.path.append but I might have done something wrong because it still doesnt work.
Any help would be much appreciated.
EDIT : still doesnt work when I write this on top of my code :
import time
import sys
sys.path.append("/path/to/dataython")
Ok. I got it now. Not a no brainer so here is the amended code :
import time
import sys
sys.path.append("path/to/your/file")
import your_file
the mistake I was doing was keep writing :
from your_file import *
I'm currently working on a project that requires I edit a configure file to replace an old standard port number if the port is being used. The code I'm currently using is the following:
import os
import sys
import socket
import select
import tempfile
import subprocess
import threading
import Queue
import time
import fileinput
...
def find_open_port():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("",0))
s.listen(1)
tempport = s.getsocketname()[1]
s.close()
return tempport
When I run it from my Ubuntu machine (Python 2.7.6) , it runs fine, but on my CentOS 6 VM running in my Redhawk Component I get the following:
AttributeError: '_socketobject' object has no attribute 'getsocketname'
Not exactly sure why I'm getting this error. Python in Redhawk is running 2.6 I want to say?
Any clue as to why this would happen and how to fix?
Your code calls the method getsockname but your error says getsocketname, you sure you copied it right when writing it to Redhawk?
I'm really enjoying Bottle so far, but the fact that I have to CTRL+C out of the server and restart it every time I make a code change is a big hit on my productivity. I've thought about using Watchdog to keep track of files changing then restarting the server, but how can I do that when the bottle.run function is blocking.
Running the server from an external script that watches for file changes seems like a lot of work to set up. I'd think this was a universal issue for Bottle, CherryPy and etcetera developers.
Thanks for your solutions to the issue!
Check out from the tutorial a section entitled "Auto Reloading"
During development, you have to restart the server a lot to test your
recent changes. The auto reloader can do this for you. Every time you
edit a module file, the reloader restarts the server process and loads
the newest version of your code.
This gives the following example:
from bottle import run
run(reloader=True)
With
run(reloader=True)
there are situations where it does not reload like when the import is inside a def. To force a reload I used
subprocess.call(['touch', 'mainpgm.py'])
and it reloads fine in linux.
Use reloader=True in run(). Keep in mind that in windows this must be under if __name__ == "__main__": due to the way the multiprocessing module works.
from bottle import run
if __name__ == "__main__":
run(reloader=True)
These scripts should do what you are looking for.
AUTOLOAD.PY
import os
def cherche(dir):
FichList = [ f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir,f)) ]
return FichList
def read_file(file):
f = open(file,"r")
R=f.read()
f.close()
return R
def load_html(dir="pages"):
FL = cherche(dir)
R={}
for f in FL:
if f.split('.')[1]=="html":
BUFF = read_file(dir+"/"+f)
R[f.split('.')[0]] = BUFF
return R
MAIN.PY
# -*- coding: utf-8 -*-
#Version 1.0 00:37
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import datetime
import ast
from bottle import route, run, template, get, post, request, response, static_file, redirect
#AUTOLOAD by LAGVIDILO
import autoload
pages = autoload.load_html()
BUFF = ""
for key,i in pages.iteritems():
BUFF=BUFF+"#get('/"+key+"')\n"
BUFF=BUFF+"def "+key+"():\n"
BUFF=BUFF+" return "+pages[key]+"\n"
print "=====\n",BUFF,"\n====="
exec(BUFF)
run(host='localhost', port=8000, reloader=True)
For some reason I'm getting a Trace/BPT trap error when calling urllib.urlopen. I've tried both urllib and urllib2 with identical results. Here is the code which throws the error:
def get_url(url):
from urllib2 import urlopen
if not url or not url.startswith('http://'): return None
return urlopen(url).read() # FIXME!
I should add that this code is running on a CherryPy webserver with web.py.
Someone requested a traceback. Unfortunately, there is none. Trace/BPT trap is outputted to the terminal and the process terminates. E.g.
dloewenherz#andros project $ sudo ./index.py 80
http://0.0.0.0:80/
# Here I visit the page which contains the get_url(url) method
Trace/BPT trap
dloewenherz#andros project $
Edit: I am running OS X 10.6.2, web.py 0.33, Python 2.6.2, and CherryPy 3.1.2.
Adding the following lines to the top of the main file solved the problem:
import urllib2
urllib2.install_opener(urllib2.build_opener())
In other words, it is not enough to import the urllib2 module but you actually need to create the opener in the main thread.
Are you running this under OS X 10.6? Apparently threads and importing modules for the first time does not play well together there. See if you can't import urllib2 outside of the thread?
There are a few more details in the following thread: Trace/BPT trap with Python threading module
I'd try either moving the import of urllib to the top of the same file or, since it seems to be a problem only with importing a module for the first time in a thread, import it somewhere else as well, like in the same file as your main() function.
Edit: Which versions of OS X, Python, CherryPy and web.py are you running? I'm using OS X 10.5.8, Python 2.6, CherryPy 3.1.2 and web.py 0.33 and can't reproduce your problem using the below code:
import web
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self):
from urllib2 import urlopen
return urlopen("http://google.se/").read()
if __name__ == "__main__": app.run()
$ sudo python index.py 80
http://0.0.0.0:80/
127.0.0.1:59601 - - [08/Nov/2009 09:46:40] "HTTP/1.1 GET /" - 200 OK
127.0.0.1:59604 - - [08/Nov/2009 09:46:40] "HTTP/1.1 GET /extern_js/f/CgJzdhICc2UgACswCjhBQB0sKzAOOAksKzAYOAQsKzAlOMmIASwrMCY4BSwrMCc4Aiw/dDWkSd2jmF8.js" - 404 Not Found
127.0.0.1:59601 - - [08/Nov/2009 09:46:40] "HTTP/1.1 GET /logos/elmo-hp.gif" - 404 Not Found
127.0.0.1:59601 - - [08/Nov/2009 09:46:40] "HTTP/1.1 GET /images/nav_logo7.png" - 404 Not Found
Is this code enough to reproduce the problem on your end? If not, I need more information in order to be of help.