有没有其他选择系统出口()在python中?

2024-10-02 12:37:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我不是问它为什么会抛出错误。我知道它引起了exceptions.SystemExit。我想知道有没有别的办法可以离开?在


Tags: if错误sysexitexceptionerrorelseexceptions
2条回答

像这样的一些问题真的应该伴随着代码背后的真正意图。原因是有些问题的解决应该完全不同。在脚本的主体中,return可用于退出脚本。从另一个角度来看,您只需记住变量中的情况,并在try/except构造之后实现想要的行为。或者您的except可能测试更显式的异常类型。在

下面的代码显示了变量的一个变体。变量被分配了一个函数(这里不调用赋值函数)。仅在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()    

os._exit()将执行低级进程退出,而不进行SystemExit或普通python退出处理。在

相关问题 更多 >

    热门问题