raw_input prints prompt after asking for input

こ雲淡風輕ζ 提交于 2021-02-10 03:55:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!