What should go to stdout/stderr and why Python logging write everything to stderr?

Grant Edwards grant.b.edwards at gmail.com
Wed Jan 4 00:20:10 EST 2023


On 2023-01-04, Chris Angelico <rosuav at gmail.com> wrote:
> On Wed, 4 Jan 2023 at 09:52, Grant Edwards <grant.b.edwards at gmail.com> wrote:
>>
>>> I can't think of a specific example, but I know I have piped the output
>>> of a program while at the same time interacting with a prompt on stderr.
>>> A rare thing, though.
>>
>> Programs that ask for passwords often do it by reading/writing to
>> fd 0 or /dev/tty so that stdout is unaffected.
>
> Reading/writing the FD is the same as using stdout.

No, stdout is fd 1.

> (technically you'd write to fd 1 and read from fd 0),

No, the whole point is _not_ to write to stdout (which would corrupt
the program's output). The way I remember it was that you wrote the
prompt to fd 0, and then read the password from fd 0. That way it
worked even when fd 1 (stdout) was redirected. It still failed if
stdin was redirected...

IIRC, you can't usually write to the stdin stream in C (or Python), so
you had to write(0,promptstr,strlen(promptstr)) instead of
printf("%s",promptstr) or fputs(promptstr,stdin).

> but yes, can use /dev/tty to reach for the console directly.

That's definitely a better option, but I'm pretty sure I've seen
multiple examples over the decades where fd 0 was used instead. Was
/dev/tty a "recent" enough invention that I would have seen
application code that was written before it existed? Or maybe I was
just looking at code written by people who weren't aware of /dev/tty?

--
Grant


More information about the Python-list mailing list