【问题标题】:How to throw error and exit with a custom message in python如何在python中抛出错误并使用自定义消息退出
【发布时间】:2014-05-03 05:38:02
【问题描述】:

我看到有人建议在 Python 中使用 sys.exit()。 我的问题是,有没有其他方法可以退出当前脚本的执行,我的意思是终止,出现错误。

类似这样的:

sys.exit("You can not have three process at the same time.")

目前我的解决方案是:

print("You can not have three process at the same time.")
sys.exit()

【问题讨论】:

  • 引发异常?对于这样的错误消息,我会写信给sys.stderrprint('You can not have three processes at the same time.', file=sys.stderr),并使用sys.exit(1) 表示错误退出代码。

标签: python error-handling


【解决方案1】:

使用字符串调用sys.exit 会起作用。 docs 明确提到了这种用法:

特别是 sys.exit("some error message") 是在发生错误时快速退出程序的方法。

【讨论】:

  • 只是从 python 文档中强调了使用 sys.exit("some error message") 的一个重要点。如果传递了另一种类型的对象,则 None 等效于传递零,并且任何其他对象都被打印到 stderr 并导致退出代码 1
【解决方案2】:

有 3 种方法,lvc 提到的第一种方法是使用 sys.exit

sys.exit('My error message')

第二种方式是使用print,print几乎可以写任何东西,包括错误信息

print >>sys.stderr, "fatal error"     # Python 2.x
print("fatal error", file=sys.stderr) # Python 3.x

第三种方法是引发我不喜欢的异常,因为它可以是try-catch

  raise SystemExit('error in code want to exit')

可以这样忽略

try:
  raise SystemExit('error in code want to exit')
except:
  print("program is still open")

【讨论】:

    【解决方案3】:

    我知道这是一个旧线程,但是您也可以引发这样的错误:

    raise SystemExit('Error: 3 个进程不能同时运行。')

    这种方法的一个优点是您不必导入 Python sys 模块。这适用于具有 Python 3 和 Python 2 的 Linux。我尚未在 Windows 或 Mac OS 上对其进行测试。

    【讨论】:

    • 在 macos w pyenv 2 和 3 上为我工作
    • 适用于 Windows 10
    【解决方案4】:

    你必须先使用import sys

    然后使用sys.exit("your custom error message")

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 2019-05-31
      • 1970-01-01
      • 1970-01-01
      • 2011-09-18
      • 2018-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多