print vs stderr

Question:

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

Asked By: Tyler

||

Answers:

They’re just two different things. print generally goes to sys.stdout. It’s worth knowing the difference between stdin, stdout, and stderr – they all have their uses.

In particular, stdout should be used for normal program output, whereas stderr should be reserved only for error messages (abnormal program execution). There are utilities for splitting these streams, which allows users of your code to differentiate between normal output and errors.

Answered By: Dan Lew

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.

Answered By: Bastien Léonard

Be careful: there are some subtleties here, including whether or not the streams are going to interactive devices. The biggest surprise is that in Python 3 stderr is line buffered (at least in Unix). For example, in a terminal window, the following prints a number every two seconds in Python 2:

for n in range(5):
    print >> sys.stderr, n,     # final comma to squelch newline character
    time.sleep(2)

whereas in Python 3, the following prints the numbers all together when the loop finishes:

for n in range(5):
    print(n, file=sys.stderr, end='')    # print n to sys.stderr with no newline char
    time.sleep(2)
Answered By: Mitchell Model

It is useful to separate stderr and stdout when running your script by redirecting them to different files. I usually use stderr for log messages and to keep track of the flow of the program, but use stdout for more useful messages that I am going to use them later.

One another way to write to stderr is as the following example:

import sys
sys.stderr.write("Error has occurred opening a file!")
Answered By: Vahid Mirjalili
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.