Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to use sys.exit(0) at the end of a Python script?

I'm learning to write Python 3 scripts to use in a shell. I have a textbook which seems to say that such a script should always use sys.exit(0) to end the script and return the code 0. Is that really necessary?

For example, suppose I run the following script with python3 foo.py:

import sys
sys.stdout.write('Hello world\n')

If I then do echo $? the response is '0'. So, the script did exit with code 0, and adding sys.exit(0) as the last line would have been redundant.

Should I leave it out, or is it still good practice?

like image 783
twsh Avatar asked Sep 29 '22 00:09

twsh


1 Answers

There is no need to use sys.exit(0) at the end of your script if no problems have been found, and it is not good practice to do so.

If you need to exit early with an error, and you don't care about the exact non-zero exit code, you can use:

raise SystemExit('error message here')

The message will be printed and return code will be 1. Otherwise, print() the message and use:

sys.exit(returncode)

to get a different returncode.

like image 158
Ethan Furman Avatar answered Oct 03 '22 02:10

Ethan Furman