How to exit a program: sys.stderr.write() or print

PythonError Handling

Python Problem Overview


I am writing a small app and I need to quit the program multiple number of times.

Should I use:

sys.stderr.write('Ok quitting')
sys.exit(1)

Or should I just do a:

print 'Error!'
sys.exit(1)

Which is better and why? Note that I need to do this a lot. The program should completely quit.

Python Solutions


Solution 1 - Python

sys.exit('Error!')

Note from the docs:

> If another type of object is passed, > None is equivalent to passing zero, > and any other object is printed to > sys.stderr and results in an exit code > of 1. In particular, sys.exit("some > error message") is a quick way to exit > a program when an error occurs.

Solution 2 - Python

They're two different ways of showing messages.

print generally goes to sys.stdout and you know where sys.stderr is going. It's worth knowing the difference between stdin, stdout, and stderr.

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, 'My error message'

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

  1. If the user redirected stdout to a file, they still see errors on the screen.
  2. It's unbuffered, so if sys.stderr is redirected to a log file there is less chance that the program will crash before the error was logged.

It's worth noting that there's a third way you can provide a closing message:

sys.exit('My error message')

This will send a message to stderr and exit.

Solution 3 - Python

If it's an error message, it should normally go to stderr - but whether this is necessary depends on your use case. If you expect users to redirect stdin, stderr and stdout, for example when running your program from a different tool, then you should make sure that status information and error messages are separated cleanly.

If it's just you using the program, you probably don't need to bother. In that case, you might as well just raise an exception, and the program will terminate on its own.

By the way, you can do

print >>sys.stderr, "fatal error"     # Python 2.x
print("fatal error", file=sys.stderr) # Python 3.x

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser225312View Question on Stackoverflow
Solution 1 - PythonunutbuView Answer on Stackoverflow
Solution 2 - PythonKushalPView Answer on Stackoverflow
Solution 3 - PythonTim PietzckerView Answer on Stackoverflow