Python: 退出脚本

Python: Exiting script

我有一个小的 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 的新手,但不是 scripting/coding。我到处搜索,每个答案都只是 "use sys.exit()"

好吧,当 sys.exit() 包含在 try/except 中时,似乎出现了意想不到的行为。如果我删除 try,它会按预期运行

这是正常行为吗?如果是这样,当 test = 2 时,有没有办法硬退出脚本而不继续执行到异常块?

注意:这是示例代码,它是我打算在另一个脚本中使用的逻辑的简化版本。 try/except 存在的原因是因为 testfunc() 将使用变量调用,如果提供了无效的函数名称,我想捕获异常

提前致谢

编辑:我也试过 quit()、exit()、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")