如何在Python中显示用户错误

发布于 2024-09-18 08:31:52 字数 88 浏览 3 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦回旧景 2024-09-25 08:31:52

在小程序中,我使用类似这样的东西:

import sys

def error(message):
    sys.stderr.write("error: %s\n" % message)
    sys.exit(1)

对于更大的工具,我使用 logging 包。

def error(message):
    logging.error('error: ', message)
    sys.exit(1)

In small programs, I use something like this:

import sys

def error(message):
    sys.stderr.write("error: %s\n" % message)
    sys.exit(1)

For bigger tools, I use the logging package.

def error(message):
    logging.error('error: ', message)
    sys.exit(1)
漆黑的白昼 2024-09-25 08:31:52

例如,在 Python 2 中:

import sys
print>>sys.stderr, "Found", numerrs, "errors in the input."
sys.exit(1)

在 Python 3(或在模块顶部带有 from __future__ import print_function 语句的 2.6 或 2.7)中,print 成为一个函数,并且现在是“打印到标准错误”的语法

print("Found", numerrs, "errors in the input.", file=sys.stderr)

(比 Python 2 中所需的奇怪的 >> 更友好的语法;-)。

print 与(例如)sys.stderr.write 的(小)优势是您可以获得“所有现代便利”:错误消息的所有部分都会自动转向转换为字符串时,它们会使用空格分隔符输出,并在最后为您输出行结束符(除非您特别要求)。要使用 sys.stderr.write,您需要构建要输出的确切字符串,通常使用字符串格式化结构——当然,这没什么大不了的,只是为了方便而已。

logging 通常是首选,但当您特别希望错误消息转到标准错误并且仅转到标准错误时,则不是: logging 提供了很多很多的可能性(发送消息不同的严重性,过滤一些,将一些放入文件,等等),但因此它不可避免地有点复杂。

In Python 2, for example:

import sys
print>>sys.stderr, "Found", numerrs, "errors in the input."
sys.exit(1)

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

print("Found", numerrs, "errors in the input.", file=sys.stderr)

(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 use sys.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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文