Something weird happened when i did this
import sys
print("Enter text: ", end="")
sys.stdin.readline()
Output:
<input>
Enter text:
(Here, <input>
(excluding quotation marks means that input happened on that line))
Why does the code run as though my code was
import sys
sys.stdin.readline()
print("Enter text: ", end="")
(Debian/Ubuntu, Python-3.8.10)
Any reason(s) for this?
CodePudding user response:
I think, that stdout
hasn't flushed before you enter your input.
Try this
import sys
print("Enter text: ", end="")
sys.stdout.flush()
sys.stdin.readline()
> Enter text: 123
CodePudding user response:
When is flushed
This answer explains the reason for flushing as newline:
Normally output to a file or the console is buffered, with text output at least until you print a newline. The flush makes sure that any output that is buffered goes to the destination.
Why this print does not flush
In your statement print("Enter text: ", end="")
you neither force the flush, nor print newline - instead end
parameter was overridden (default was \n
new line). Thus the specified text is printed to buffer only and not yet flushed to console.
How to force flush
Built-in function print()
has a parameter named flush
which default is False
:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
[..] Whether the output is buffered is usually determined by file, but if the
flush
keyword argument is true, the stream is forcibly flushed.