如何在python中抛出错误并使用自定义消息退出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22633544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:19:20  来源:igfitidea点击:

How to throw error and exit with a custom message in python

python

提问by Mostafa Talebi

I've seen people suggesting sys.exit() in Python. My question is that, is there any other way to exit the execution of current script, I mean termination, with an error.

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

Something like this:

像这样的东西:

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

Currently my solution would be:

目前我的解决方案是:

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

采纳答案by lvc

Calling sys.exitwith a string will work. The docsmention this use explicitly:

sys.exit使用字符串调用将起作用。该文件明确提到这一点:

In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.

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

回答by Osian

I know this is an old thread, however you can also raise an error like this:

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

raise SystemExit('Error: 3 processes cannot run simultaneously.')

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

One advantage of this approach is that you don't have to import the Python sys module. This works on Linux with Python 3 and Python 2. I have not tested it on Windows or Mac OS.

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

回答by nima moradi

There are 3 approaches, the first as lvc mentioned is using sys.exit

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

sys.exit('My error message')

The second way is using print, print can write almost anything including an error message

第二种方法是使用print, print 几乎可以写入任何内容,包括错误消息

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

The third way is to rise an exception which I don't like because it can be try-catch

第三种方法是提出一个我不喜欢的例外,因为它可以 try-catch

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

it can be ignored like this

它可以像这样被忽略

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

回答by Dasun

You have to use import sysfirst

你必须使用import sys第一

Then use sys.exit("your custom error message")

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