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

20

u/shiftybyte Mar 05 '21

This is actually really interesting... will this solve your problem?

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

27

u/[deleted] Mar 05 '21

Yes, it will solve my problem, but print() by default appends a newline, so there should be an end='' argument:

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

I was looking for a way to print the prompt properly with a single call to input(), but if that isn't possible, I'm probably going to use this solution.

Thanks!

4

u/aroberge Mar 06 '21

How about redefining input? Something (untested) like:

old_input = input
def input(prompt):
    print(prompt, end='')
    return old_input()