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

跟風遠走 提交于 2019-12-08 14:20:37

问题


try:
 x="blaabla"
 y="nnlfa"   
 if x!=y:
        sys.exit()
    else:
        print("Error!")
except Exception:
    print(Exception)

I'm not asking about why it is throwing an error. I know that it raises exceptions.SystemExit. I was wondering if there was another way to exit?


回答1:


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



回答2:


os._exit() will do a low level process exit without SystemExit or normal python exit processing.



来源:https://stackoverflow.com/questions/38511096/is-there-an-alternative-for-sys-exit-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!