Reputation: 143
I wrote the following code in Python IDLE, using its editor
import urllib.request
print(urllib.request.urlopen('https://github.com').read().decode('utf-8'))
and then saved the code as a script. After I ran the script, Python displayed the page source I want.
When I changed the above code to:
import urllib.request
urllib.request.urlopen('https://github.com').read().decode('utf-8')
and then ran the script, Python displayed nothing. This is understandable.
The weird thing for me, however, is that if I run the above code (the one without print
) interactively in a Python shell, Python shell can still display the page source, as you see:
>>> import urllib.request
>>> urllib.request.urlopen('https://github.com').read().decode('utf-8')
'\n\n\n\n\n\n<!DOCTYPE html>\n<html\n lang="en"\n \n \n ...'
(output snipped)
I don't understand why.
Upvotes: 1
Views: 1603
Reputation: 491
It's because the shell is printing the result of execution. If you assign the function call to a variable then it will suppress the printing.
i.e. html = urllib.request.urlopen( ... )
Upvotes: 1
Reputation: 9427
You are using the interactive python prompt. It automatically prints return values for you so that you can see the result of what you're doing.
Try typing 3 + 2
. You know this doesn't print anything either - but you will see the result.
Likewise, if you put those two lines into a file you won't get any output.
Upvotes: 5