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

Question:

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.

Asked By: user225312

||

Answers:

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
Answered By: Tim Pietzcker
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.

Answered By: unutbu

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.

Answered By: KushalP
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.