Home > Blockchain >  Continue executing a for loop is a specific system exit is raised in Python
Continue executing a for loop is a specific system exit is raised in Python

Time:09-19

I have a function that has multiple sys.exit() exceptions. I am calling the function iteratively and want my loop to continue if a certain sys.exit() is raised while error out for all others. The sample code can be something like:

def exit_sample(test):

        if test == 'continue':
            sys.exit(0)
        else:
            sys.exit("exit")

list = ["continue", "exit", "last"]
for l in list:
        try:
            exit_sample(l)
        except SystemExit:
            print("Exception 0")
            

In the current form, the code will not error out but will print 'Exception 0' every time. I want it to not error out the first time, and then exit when l = "exit". How can that be done?

CodePudding user response:

Store the exception in a variable and check if the code (or other characteristics) matches your condition for continuing your code. I modified your code such that it will continue if the exit code is 0 and otherwise re-raises system exit

import sys

def exit_sample(test):
    if test == 'continue':
        sys.exit(0)
    else:
        sys.exit("exit")

list = ["continue", "exit", "last"]

for l in list:
    try:
        exit_sample(l)
    except SystemExit as exc:
        if exc.code == 0:
            print("continuing")
        else:
            # raise previous exception
            raise

CodePudding user response:

You can catch the exception, check if it is the one that justifies continue and re-raise it if it does not.

import sys

def exit_sample(test):
    if test == 'continue':
        sys.exit(0)
    else:
        sys.exit("exit")

lst = ["continue", "exit", "last"]
for l in lst:
    try:
        exit_sample(l)
    except SystemExit as ex:      # catch the exception to variable
        if str(ex) == "0":        # check if it is one that you want to continue with
            print("Exception 0")
        else:                     # if not re-raise the same exception.
            raise ex

CodePudding user response:

What you want is to convert the exception to a string and compare that with "exit". After seeing if it works, you can remove the print statement.

import sys

def exit_sample(test):
    if test == 'continue':
        sys.exit(0)
    else:
        sys.exit("exit")

list = ["continue", "exit", "last"]
for l in list:
    try:
        exit_sample(l)
    except SystemExit as error:
        print(error)
        if str(error) == "exit":
            sys.exit("foo")
  • Related