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(),任何建议…!!!!
此处发布的代码包含所有版本详细信息。
我已经尝试了所有可能的方法来触发它,但是我失败了。它到达"例外"区。
提前谢谢……
请参见此示例:
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 whenos._exit() is called.
号
因此,如果在提升
现在,从编程的角度来看,您基本上不需要把您知道的东西放在
方法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) |