r/learnpython • • Mar 05 '21

Python input() function writes prompt to standard error instead of standard output

I'm using Python 3.9.2 on Arch Linux.

I'm trying to make an interactive shell program in Python. I ran into an issue where the shell prompt would sometimes come before the output of the previous command. Here's a small example program that demonstrates the issue:

while True:
    cmd=input('>>> ')
    print('This is the output')

Around 80% of the time, the program works as expected:

>>> hello
This is the output
>>> goodbye
This is the output
>>> test
This is the output

However, occasionally, this happens:

>>> hello
>>> This is the output

As you can see, on the second line, the >>> prompt is printed before This is the output is printed.

I tried to use strace to debug the program, and I found out that the input() function actually writes the prompt to standard error, not standard output (when the program is run interactively). Here are the relevant syscalls:

write(2, ">>> ", 4)                     = 4
read(0, "hello\n", 1024)                = 6
write(1, "This is the output\n", 19)    = 19
write(2, ">>> ", 4)                     = 4

You can see from the syscalls that the print() function writes to file descriptor 1 (standard output), but the input() function writes to file descriptor 2 (standard error).

This seems to contradict what the documentation says:

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

Is there a way to force input() to write the prompt to standard output instead of standard error?

362 Upvotes

23 comments sorted by

View all comments

127

u/debian_miner Mar 05 '21

Looks like this was reported as a bug: https://bugs.python.org/issue25692.

Edit: You can work around your issue by calling sys.stdout.flush() before your call to input()

47

u/[deleted] Mar 05 '21

Thanks for finding the bug report!

I was able to get input() to output the prompt to standard output by adding import readline to the top of the file. This also has the benefit of allowing me to use GNU Readline for user input.