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