10

I'm using a Python script to farm out some subprocesses to some other Python scripts. I need to make sure the Python subprocesses run successfully. Is there a convention on whether it is better to exit(0) or return 0 at the end of a successfully run Python script?

I don't think it matters from a functional perspective, but I'm wondering whether one is preferred.

2
  • I think sys.exit(0) is more clear, also checkout the errno module for standard exit codes. May 8, 2014 at 16:35
  • 2
    erm... python does not have a main function so your choice is to call sys.exit or not calling it. There's no such a thing as return 0, since it would raise a SyntaxError when outside a function.
    – Bakuriu
    May 8, 2014 at 16:40

1 Answer 1

15

You shall always use sys.exit(exit_code)

return 0 will not be seen on system level.

Following (wrong) code:

if __name__ == "__main__":
    return 0

is wrong and complains on last line, that there is standalone return outside a function

Trying this will not complain, but will not be seen on system level:

def main():
    return 0

if __name__ == "__main__":
    main()

Correct is:

import sys

def main():
    sys.exit(0)

if __name__ == "__main__":
    main()
2
  • Does exit(0) vs sys.exit(0) matter?
    – Phil Braun
    May 8, 2014 at 16:50
  • 2
    @PhilBraun I have always seen only import sys followed by sys.exit(0). Other option (which I do not recall to see) is from sys import exit followed by exit(0). But your question made me to test, if I can call exit without importing from sys and it really works (Python 2.7.6). So it works, but I would recommend using the import sys followed by sys.exit(code) idiom. May 8, 2014 at 18:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.