[Solved] Is there an alternative for sys.exit() in python?


Some questions like that should really be accompanied by the real intention behind the code. The reason is that some problems should be solved completely differently. In the body of the script, the return can be used to quit the script. From another point of view, you can just remember the situation in a variable and implement the wanted behaviour after the try/except construct. Or your except may test more explicit kind of an exception.

The code below shows one variation with the variable. The variable is assigned a function (the assigned function is not called here). The function is called (via the variable) only after the try/except:

#!python3

import sys

def do_nothing():
    print('Doing nothing.')

def my_exit():
    print('sys.exit() to be called')
    sys.exit()    

fn = do_nothing     # Notice that it is not called. The function is just
                    # given another name.

try:
    x = "blaabla"
    y = "nnlfa"   
    if x != y:
        fn = my_exit    # Here a different function is given the name fn.
                        # You can directly assign fn = sys.exit; the my_exit
                        # just adds the print to visualize.
    else:
        print("Error!")
except Exception:
    print(Exception)

# Now the function is to be called. Or it is equivalent to calling do_nothing(),
# or it is equivalent to calling my_exit(). 
fn()    

solved Is there an alternative for sys.exit() in python?