3

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.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Zazman
  • 51
  • 2
  • Is this running in a script at a regular terminal, an IDE's terminal, IDLE, something else? Likely it's an issue with a terminal emulator that doesn't quite support the features `raw_input` uses to flush `sys.stdout` prior to displaying the prompt. – ShadowRanger Sep 26 '18 at 04:27
  • Likely related to [raw_input() won't show prompt until after input](https://stackoverflow.com/q/11621082/364696), but the answer there is poor; not willing to mark as duplicate. – ShadowRanger Sep 26 '18 at 04:30
  • I am running with a Git bash terminal, but when I run it in CMD it works. – Zazman Sep 26 '18 at 05:10

2 Answers2

0

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
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

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.

Zazman
  • 51
  • 2