问题
When I use raw_input, the prompt only shows after the user gives input. Like this:
number = raw_input("Enter a number:")
but when I run this, nothing happens, the I type a number, the it shows the prompt:
123
Enter a number:
(123 used to be blank until I typed a number and hit enter)
I just want the prompt to display before the user input. If anybody knows how to fix this please help.
Thanks.
回答1:
You might be in an environment where your standard output is buffered and won't flush until there is a newline character.
You can take advantage of the fact the standard error is unbuffered and redirect standard output to standard error instead:
import sys
sys.stdout = sys.stderr
回答2:
Thanks for you suggestion, and I did try that, but unfortunately it didn't work, but I did find the solution:
I had to add
sys.stdout.flush()
before each time I had a
variable = raw_input("A prompt")
to flush the buffer.
Although for the first
raw_input("A prompt")
it will not work work unless you already printed something, for example
variable = raw_input("A prompt")
sys.stdout.flush()
would still have the same issue, whereas
print"Welcome,"
variable = raw_input("A prompt")
sys.stdout.flush()
would work.
来源:https://stackoverflow.com/questions/52509889/raw-input-prints-prompt-after-asking-for-input