python sys.exit没有在try中工作

python sys.exit not working in try

本问题已经有最佳答案,请猛点这里访问。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Python 2.7.5 (default, Feb 26 2014, 13:43:17)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type"help","copyright","credits" or"license" for more information.
>>> import sys
>>> try:
...  sys.exit()
... except:
...  print"in except"
...
in except
>>> try:
...  sys.exit(0)
... except:
...  print"in except"
...
in except
>>> try:
...  sys.exit(1)
... except:
...  print"in except"
...
in except

为什么不能在try中触发sys.exit(),任何建议…!!!!

此处发布的代码包含所有版本详细信息。

我已经尝试了所有可能的方法来触发它,但是我失败了。它到达"例外"区。

提前谢谢……


sys.exit()提出一个例外,即SystemExit。这就是为什么你降落在江户区的原因。

请参见此示例:

1
2
3
4
5
6
import sys

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

这给了你:

1
<type 'exceptions.SystemExit'>

虽然我不能想象有任何实际的理由这样做,但是您可以使用这个构造:

1
2
3
4
5
6
7
8
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


基于python wiki:

Since exit() ultimately"only" raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.

还有:

The exit function is not called when the program is killed by a signal, when a Python fatal internal error is detected, or when os._exit() is called.

因此,如果在提升SystemExit异常后在try块python中使用sys.exit(),python拒绝完成exits的功能并执行exception块。

现在,从编程的角度来看,您基本上不需要把您知道的东西放在try块中,这肯定会引发异常。相反,您可以手动提出一个SystemExit异常,或者作为一种更纯粹的方法,如果您不想失去sys.exit()的各自功能,比如向其构造函数传递可选参数,您可以在finallyelse甚至except块中调用sys.exit()

方法1(不推荐)

1
2
3
4
5
6
7
8
9
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(推荐):

1
2
3
4
5
6
7
8
9
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)