Phil Braun
Phil Braun

Reputation: 591

Exit 0 vs. Return 0 Python Preference

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.

Upvotes: 11

Views: 13580

Answers (1)

Jan Vlcinsky
Jan Vlcinsky

Reputation: 44102

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()

Upvotes: 17

Related Questions