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

5

u/exhuma exhuma Mar 06 '21

Top notch question! It makes me believe that you have experience but are only now getting into Python. So while I generally avoid answers like "you shouldn't do it this way. Do X instead" as those are really not helpful for a learner at all.

But I wager that you are not a beginner.

With that out of the way, if the script you are writing is not just an exercise for learning Python, but part of an application which you do intend to use in the future, have a look at the stdlib cmd module or even prompt-toolkit which will give you a nicer user-experience without much more effort.

1

u/[deleted] Mar 08 '21

Thanks for the links, I'll look into them!