【发布时间】:2019-07-05 11:19:02
【问题描述】:
我有一个专门针对这个问题编写的小型 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")
我所期待的是,当 test = 2 时,脚本应该退出。相反,我得到的是这个;
test is not 1
something went wrong
if test is not 1 it should not print this
我是 python 新手,但不是脚本/编码新手。我到处搜索,每个答案都只是“使用 sys.exit()”
嗯,当它包含在 try/except 中时,sys.exit() 似乎有一些意想不到的行为。如果我删除 try 它的行为符合预期
这是正常行为吗?如果是这样,有没有办法在 test = 2 时硬退出脚本而不继续执行到异常块?
注意:这是示例代码,它是我打算在另一个脚本中使用的逻辑的简化版本。 try/except 存在的原因是因为 testfunc() 将使用变量调用,如果提供了无效的函数名,我想捕获异常
提前致谢
编辑:我也尝试过 quit()、exit()、os._exit() 和 raise SystemExit
【问题讨论】:
标签: exit