1

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?

  • 1
    @Eugenij answer is correct. I want to add that you can use the built in `input` function for what you are doing here. The 3 lines of code would become: `input("Enter text: ")` – hamdanal Dec 26 '21 at 11:09

2 Answers2

1

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
Yevhen Bondar
  • 4,357
  • 1
  • 11
  • 31
  • 2
    Or you could do ```print("Enter text: ", flush=True, end="") sys.stdin.readline()``` –  Dec 26 '21 at 11:04
  • @Allearthstuffs Great communty-sense to help and comment on other answers ️ Try your own answer, it is exactly the way to flush. – hc_dev Dec 26 '21 at 11:21
1

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.

See also

hc_dev
  • 8,389
  • 1
  • 26
  • 38
  • So, when you do ```print("text")``` it flushes ```sys.stdout``` when the output stream or python interpreter reaches a newline, but when you do ```print("text", end="")``` the output stream or python interpreter does not detect the newline, so is just added to memory (buffer), and then ```sys.stdin.readline()``` returns a newline, then the output stream is flushed and you see ```text``` in the console . . . –  Dec 28 '21 at 12:31
  • @Allearthstuffs: Exactly, as far as I suppose, that newline from `readline()` effects the flushing. The `print("text")` uses default argument `end = '\n'` which wraps on console and effects flushing, while your `print("text", end="")` does not wrap and thus not flushes. – hc_dev Dec 28 '21 at 12:46