如何在Python中显示用户错误
在 Python 中向用户显示错误的最佳方式(标准)是什么(例如:错误的语法、无效的参数、逻辑错误)?
该方法应该在标准错误中打印错误并退出程序。
What is the best way (standard) to display an error to the user in Python (for example: bad syntax, invalid arguments, logic errors)?
The method should print the error in the standard error and exit the program.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在小程序中,我使用类似这样的东西:
对于更大的工具,我使用
logging
包。In small programs, I use something like this:
For bigger tools, I use the
logging
package.例如,在 Python 2 中:
在 Python 3(或在模块顶部带有
from __future__ import print_function
语句的 2.6 或 2.7)中,print
成为一个函数,并且现在是“打印到标准错误”的语法(比 Python 2 中所需的奇怪的
>>
更友好的语法;-)。print
与(例如)sys.stderr.write
的(小)优势是您可以获得“所有现代便利”:错误消息的所有部分都会自动转向转换为字符串时,它们会使用空格分隔符输出,并在最后为您输出行结束符(除非您特别要求)。要使用 sys.stderr.write,您需要构建要输出的确切字符串,通常使用字符串格式化结构——当然,这没什么大不了的,只是为了方便而已。logging
通常是首选,但当您特别希望错误消息转到标准错误并且仅转到标准错误时,则不是:logging
提供了很多很多的可能性(发送消息不同的严重性,过滤一些,将一些放入文件,等等),但因此它不可避免地有点复杂。In Python 2, for example:
In Python 3 (or 2.6 or 2.7 with the
from __future__ import print_function
statement at the top of your module),print
becomes a function and the syntax for "printing to standard error" is now(a somewhat more friendly syntax than the strange
>>
needed in Python 2;-).The (small) advantage of
print
versus (say)sys.stderr.write
is that you get "all the modern conveniences": all parts of the error message are automatically turned into strings, they're output with space separators, and a line-end is output for you at the end (unless you specifically request otherwise). To usesys.stderr.write
, you need to build the exact string to output, typically using string-formatting constructs -- not a big deal, of course, just a small matter of convenience.logging
is usually preferred, but not when you specifically want the error message to go to standard error, and to standard error only:logging
offers many, many more possibilities (send messages of various severity, filter some, put some to files, and so on), but therefore it's inevitably a little bit more complex.