这个问题已经在这里有一个答案:
我有我已经为这个问题专门写了一个小python脚本。
#!/usr/bin/python3
import sys
def testfunc(test):
if test == 1:
print("test is 1")
else:
print("test is not 1")
sys.exit(0)
try:
testfunc(2)
except:
print("something went wrong")
print("if test is not 1 it should not print this")
我所期待的是,当测试= 2的脚本应该退出。相反,我所得到的是这样的;
test is not 1
something went wrong
if test is not 1 it should not print this
我是新来的Python而不是脚本/编码。我已经找遍了所有的地方,每个答案很简单,“使用sys.exit()”
那么它似乎sys.exit()有什么似乎是当它被包含在try /除了意外行为。如果我删除其行为与预期的尝试
这是正常的行为呢?如果是的话是有办法严出与出它继续执行到异常块时测试= 2的脚本?
注:这是示例代码,我打算在另一个脚本中使用逻辑的简化版本。在尝试不同的是有因为testfunc()将使用一个变量进行调用,我想捕捉异常,如果提供/无效的函数名的原因
提前致谢
编辑:我也曾尝试戒烟(),出口(),os._exit()和raise SystemExit
在这里,sys.exit(0)
raises一个SystemExit
例外。
既然你把调用代码Try-Except
块内,它的预期捕获。如果你想传播例外,回想与代码状态sys.exit()
:
try:
testfunc(2)
except SystemExit as exc:
sys.exit(exc.code) # reperform an exit with the status code
except:
print("something went wrong")
print("if test is not 1 it should not print this")