Search code examples
pythonstdoutstderr

When to use sys.stdout instead of sys.stderr?


My boss told me to look at some old code where everything is being sent to stderr. I know that stderr should have the warnings and errors, but when should they really should go to stdout instead?

This program is a service. Some of the messages that it sends to stderr are:

if pid is None:
    message = "pidfile {0} is not running. \n"
    sys.stderr.write(message.format(self.pidfile))

So this one is an output, right? A message about being successful or not should go to stdout, because it's not an error?

And then I got another one that is an exception:

except OSError as err:
    sys.stderr.write('fork #1 failed: {0}\n'.format(err))
    sys.exit(1)

This one as an exception, so it should go to stderr, because it's an error? Or should it go to stdout, because it is a output message just saying that the program failed?

I know what stdout and stderr are --- I read quite a bit before asking. My problem here is being able to identify which messages should go to stderr --- just fatal errors, or any kind of error message?

Both the examples are error messages, but one is just a "Program is not running". I'm having trouble choosing where that kind of message should be sent.


Solution

  • Fatal errors should certainly go to stderr. Normal output should go to stdout.

    There is a gray area for informative messages, but in general they should not go to stdout if they would render the output unusable. People will often direct stdout to a file and stderr to either the terminal or a log file.

    You need to decide what division makes the most sense.