【问题标题】:Python: Exiting script [duplicate]Python:退出脚本[重复]
【发布时间】: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


    【解决方案1】:

    这里,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")
    

    【讨论】:

    • 感谢 Amessihel,我尝试了您的代码并且它有效,我会将其合并到我的脚本中。我假设在 python 中没有硬退出的选项,例如 php die() 或 bash exit?
    • @brettg,根据我所看到的,我不这么认为。但是我对 Python 不熟悉。
    猜你喜欢
    • 2014-05-01
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 2019-08-08
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多