简体   繁体   中英

How to use multiple sys.exit() with different return codes inside a try except block in python

I have a python script which is called as a subprocess from a parent script. In this script I have multiple if statements inside a try block and I do sys.exit() with different return code from these if statements. The structure of the code is this way:

def func3():

    try:

        # bunch of other code
        if condition1:
            print 'condition 1'
            sys.exit(1)
        if condition2:
            print 'condition 2'
            sys.exit(0)
         .
         .
         .


    except:
        print 'In the except'
        #what sys.exit() to put here

if __name__ == '__main__':

    func3()

I know it is not a good way to write this way but I have to use try as there are many different parts of the code which may result in some error and also the if conditions depends on the execution and result of these codes.

Now the problem is that how can I put this code so that it successfully does a sys.exit() with appropriate exit code. What sys.exit() should I put in the except section as if I do a sys.exit(1) from inside the try and sys.exit(0) from inside the except then the return code will be 0 instead of 1 .

You are playing Pokemon here; you are catching them all . Don't do that.

At most catch Exception ; the SystemExit exception thrown by sys.exit() doesn't inherit from Exception (only from BaseException ) and will simply be passed through:

try:
    # ...
except Exception:
    # ...

SystemExit , together with GeneratorExit and KeyboardInterrupt should rarely be caught anyway, which is why they are the only 3 exceptions that do not derive from Exception . See the Exception hierarchy documentation .

If you must catch the SystemExit , you can read the exit code from the code attribute:

try:
    # ...
except SystemExit as sysexit:
    sys.exit(sysexit.code)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM