views:

5885

answers:

3

Are there any specific advantages or disadvantages to either?

+7  A: 

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.

Daniel Lew
Also note that stderr is unbuffered, which can be useful.
JimB
I’d tweak the wording of your answer to replace “program output” with “non-textual or non-status program output”. stderr also should not be reserved for error messages in all cases — for example, a program that downloads to stdout, which gets piped to another program, but prints download progress into stderr (which gets to ‘break out’ of the pipe).
Jeremy Visser
+24  A: 

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.
Bastien Léonard
+6  A: 

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)
Mitchell Model