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.
exit() function allows the developer to exit from Python. The exit function takes an optional argument, typically an integer, that gives an exit status. Zero is considered a “successful termination”.
Functions of Stderr in C with Examples. Stderr is the standard error message that is used to print the output on the screen or windows terminal. Stderr is used to print the error on the output screen or window terminal. Stderr is also one of the command output as stdout, which is logged anywhere by default.
Python stderr is known as a standard error stream. It is similar to stdout because it also directly prints to the console but the main difference is that it only prints error messages. After writing the above code (python print to stderr), you can observe that it print debug message using sys. stderr.
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:
stdout
to a file, they still see errors on the screen.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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With