How to import and use a module with one line

Question:

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]))

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

Asked By: Jerfov2

||

Answers:

You always need the import, however you can still use semi-colons to separate statements:

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 ^
Answered By: Zizouz212

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]))
Answered By: mnieber
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.