I observed a strange behaviour of the __future__ module’s print_function in Python 3.2.
Take, for example this code:
from __future__ import print_function
import sys
print('Enter the base path of the images: ', end='')
path = sys.stdin.readline().strip().strip('"')
if len(path) == 0:
print("No path entered")
else:
print(root)
print("\n\nPress ENTER to exit")
exit = sys.stdin.readline()
When the script is run, it appears the console waits for the user to press ENTER before displaying the first print statement.
The output then looks like this:
Enter the base path of the images: No path entered Press ENTER to exit
Needless to day, displaying an empty prompt to the user leads to a lot of confusion especially since a lot of people are afraid of the black window with white text (Command Prompt).
When the code is changed to this
from __future__ import print_function
import sys
print('\nEnter the base path of the images: ', end='') #line now starts with \n
path = sys.stdin.readline().strip().strip('"')
if len(path) == 0:
print("No path entered")
else:
print(path)
print("\n\nPress ENTER to exit")
exit = sys.stdin.readline()
Then the output is as expected (assuming we ignore the preceding empty line):
Enter the base path of the images: c:\ c:\ Press ENTER to exit
When the code is run in python 2.6 however, the first one works as expected (i.e. it displays Enter the base path of the images: before waiting to receive input).
This leads me to ask:
Why do I need to precede the print function with a \n in order to get an output displayed in Python 3.2 while I don’t need the \n when running in Python 2.6?
Could it be that the print_function is implemented differently in the two versions?
You are seeing the effects of line buffering. Flush
stdoutfirst (usingsys.stdout.flush()for backwards compatibility with Python 2):The
print()function in Python 2 is certainly different from the one in Python 3 (where thefrom __future__ import print_functionline is effectively meaningless). In Python 3, I/O has been overhauled andstdoutbuffering semantics have changed subtly. In Python 2, thesys.stdin.readline()call flushesstdoutautomatically, in Python 3 this is no longer the case.If you use the
input()function instead of reading fromstdindirectly, you do not need to flush at all: