Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python How To Import And Use Module With One Line

My question is a fairly straight-forward one. I have this code that loads the natural gas storage numbers from the internet.

from urllib.request import urlopen
print(int(str(urlopen("http://ir.eia.gov/ngs/wngsr.txt").read()).split("\\n")[4].split(" ")[2]))

What I want to know is, how could I do this in one line? More specifically, I was wondering how I could get rid of the import line and do something like this:

print(int(str(urllib.request.urlopen("http://ir.eia.gov/ngs/wngsr.txt").read()).split("\\n")[4].split(" ")[2]))

(I changed the urlopen call to urllib.request.urlopen) It would be sort of like Java, if you use the fully qualified name, you don't need an import statement. Do you know any way to do this? Thanks!

like image 403
Jerfov2 Avatar asked Jun 05 '15 02:06

Jerfov2


2 Answers

When trying out the suggestion by Zizouz212, I found this works

print(int(str(__import__('urllib').request.urlopen("http://ir.eia.gov/ngs/wngsr.txt").read()).split("\\n")[4].split(" ")[2]))
like image 149
mnieber Avatar answered Oct 24 '22 08:10

mnieber


You always need the import, however you can still use semi-colons to separate statements, but why would you do that?

from urllib.request import urlopen; print(int(str(urllib.request.urlopen("http://ir.eia.gov/ngs/wngsr.txt").read()).split("\\n")[4].split(" ")[2]))
#             note the semi-colon ^
like image 44
Zizouz212 Avatar answered Oct 24 '22 09:10

Zizouz212