Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 432
user225312 Avatar asked Jun 01 '10 13:06

user225312


People also ask

What is the purpose of the sys exit () function?

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”.

Is stderr printed?

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.

What does Sys stderr do in Python?

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.


2 Answers

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.

like image 185
unutbu Avatar answered Oct 01 '22 05:10

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.

like image 21
KushalP Avatar answered Oct 01 '22 04:10

KushalP