Are there any specific advantages or disadvantages to either?
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.
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.
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)