Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit 0 vs. Return 0 Python Preference

Tags:

python

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.

like image 654
Phil Braun Avatar asked May 08 '14 16:05

Phil Braun


Video Answer


1 Answers

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()
like image 101
Jan Vlcinsky Avatar answered Sep 23 '22 00:09

Jan Vlcinsky