Wrap main() function in sys.exit() callback
I'm used to writing Python scripts with a final function block that reads:
if __name__ == "__main__":
main()
Meaning, "if the Python script is run as the main program (as opposed to being imported as a module), then execute the main()
function."
When working on a recent script, my Copilot autocomplete suggested a more complex signature:
def main():
try:
do_something = something()
print("We did something!")
return 0
except Exception as e:
print(f"Error message: {e}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())
This is a best practice way to connect the output of the main()
function to the main exit codes that a command-line application should provide: 0
for exited successfully and 1
for exited with an error."
So here we:
-
write the
main()
function in such a way as to return either0
or1
based on the outcome of ourtry...except
block; and -
wrap the
main()
function in thesys.exit()
call, so that theexit()
function will receive that output, and the program will exit with an appropriate execution code.