I am writing a small app and I need to quit the program multiple number of times.
Should I use:
开发者_Python百科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.
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.
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:
- If the user redirected
stdout
to a file, they still see errors on the screen. - 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.
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
精彩评论