Why does the Python shell output something even when there is no "print" command?
Question:
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 shell 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 shell 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:
I don’t understand why.
I use Python 3.6.3.
Answers:
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.
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( ... )
How do I avoid printing the result of execution, Only If I have print statement I want it to be printed. Any help experts on this.
Regards
Kanni
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 shell 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 shell 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:
I don’t understand why.
I use Python 3.6.3.
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.
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( ... )
How do I avoid printing the result of execution, Only If I have print statement I want it to be printed. Any help experts on this.
Regards
Kanni