print vs stderr

Tyler picture Tyler · Jun 2, 2009 · Viewed 58.5k times · Source

Are there any specific advantages or disadvantages to either print or stderr?

Answer

Bastien Léonard picture Bastien Léonard · Jun 2, 2009

print can print on any file-like object, including sys.stderr.

print >> sys.stderr, 'Text'

The advantages of using sys.stderr for errors instead of sys.stdout are:

  • If the user redirected stdout to a file, she still sees errors on the screen.
  • It's not buffered, so if sys.stderr is redirected to a log file there are less chance that the program may crash before the error was logged.

This answer written with Python 2 in mind. For Python 3, use print('Text', file=sys.stderr) instead.