问题 python sys.exit无法在try [duplicate]中工作


这个问题在这里已有答案:


2374
2017-09-18 06:42


起源

我把它作为副本关闭,因为另一篇文章解释了a)出了什么问题,以及b)如何避免这种情况。毯 except: 条款不是一个好主意,充分利用 except Exception: 避免捕捉 SystemExit。 - Martijn Pieters♦
如果您不想触发异常,请使用os._exit(0)。 - Back2Basics
@ Back2Basics: 别 呼叫 os._exit();只是确保在处理器退出时不会清理任何东西。 - Martijn Pieters♦


答案:


sys.exit() 提出了一个例外,即 SystemExit。这就是你登陆的原因 except-块。

看这个例子:

import sys

try:
    sys.exit()
except:
    print(sys.exc_info()[0])

这给你:

<type 'exceptions.SystemExit'>

虽然我无法想象一个人有任何实际的理由这样做,你可以使用这个结构:

import sys

try:
    sys.exit() # this always raises SystemExit
except SystemExit:
    print("sys.exit() worked as expected")
except:
    print("Something went horribly wrong") # some other exception got raised

12
2017-09-18 06:47



在try块中有没有办法做到这一点。 - onlyvinish
没有理由,因为你试图实现的是提出异常 try 并在下一刻“抓住”它。这绝对是无能为力的;-) - tamasgal
使用 except Exception因为 SystemExit 直接继承自 BaseException。见 异常层次结构 - Vincent
谢谢哥们..!!如果您对此有任何想法,请及时更新我。 - onlyvinish
@onlyvinish他已经给了你一个主意!还有什么你想念的? - glglgl


基于python wiki:

以来 出口() 最终“only”引发异常,它只会在从主线程调用时退出进程,并且异常不会被截获。

和:

exit 当程序被信号杀死时,当检测到Python致命内部错误时,或者何时被调用时,不会调用函数 os._exit() 叫做。

因此,如果你使用 sys.exit() 在一个 try 提升之后阻止python SystemExit 异常python拒绝完成 exits的功能和执行 exception 块。

现在,从编程的角度来看,你基本上不需要放一些你知道肯定会引发异常的东西 try 块。相反,你可以提出一个 SystemExit 例如,如果您不想放弃相应的功能,请手动执行或作为更多Pythonic方法 sys.exit() 比如将可选参数传递给它可以调用的构造函数 sys.exit() 在一个 finallyelse 甚至 except 块。

方法1(不推荐)

try:
    # do stuff
except some_particular_exception:
    # handle this exception and then if you want 
    # do raise SystemExit
else:
    # do stuff and/or do raise SystemExit
finally:
    # do stuff and/or do raise SystemExit

方法2(推荐):

try:
    # do stuff
except some_particular_exception:
    # handle this exception and then if you want 
    # do sys.exit(stat_code)
else:
    # do stuff and/or do sys.exit(stat_code)
finally:
    # do stuff and/or do sys.exit(stat_code)

4
2017-09-18 06:51



不要打电话 os._exit() 你自己,*只是不要抓住 SystemExit。调用 os._exit() 意味着没有任何东西得到清理。 - Martijn Pieters♦