Python:抑制进入命令行的错误?
当我尝试从命令行执行 python 程序时,出现以下错误。这些错误不会对我的输出造成任何问题。我不希望它显示在命令行中
Traceback (most recent call last):
File "test.py", line 88, in <module>
p.feed(ht)
File "/usr/lib/python2.5/HTMLParser.py", line 108, in feed
self.goahead(0)
File "/usr/lib/python2.5/HTMLParser.py", line 148, in goahead
k = self.parse_starttag(i)
File "/usr/lib/python2.5/HTMLParser.py", line 226, in parse_starttag
endpos = self.check_for_whole_start_tag(i)
File "/usr/lib/python2.5/HTMLParser.py", line 301, in check_for_whole_start_tag
self.error("malformed start tag")
File "/usr/lib/python2.5/HTMLParser.py", line 115, in error
raise HTMLParseError(message, self.getpos())
HTMLParser.HTMLParseError: malformed start tag, at line 319, column 25
我怎样才能抑制错误?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
捕获 HTMLParseError 对您不起作用吗?如果
test.py
是你的 python 文件的名称,它会传播到那里,所以它应该。这是如何抑制此类错误的示例。您可能需要稍微调整它以匹配您的代码。
您还可以通过将 stderr 重定向到 null 来抑制错误消息,就像 Ignacio 建议的那样。要在代码中执行此操作,您可以编写以下内容:
但是,这可能不是您想要的,因为从您的错误来看,脚本执行似乎已停止,并且您可能希望继续执行。
Doesn't catching HTMLParseError work for you? If
test.py
is the name of your python file, it's propagated up to there, so it should.Here's an example how to suppress such an error. You might want to tweak it a bit to match your code.
You can also just suppress the error message by redirecting stderr to null, like Ignacio suggested. To do it in code, you can just write the following:
However, this is probably not be what you want, because from your error it looks like the script execution is stopped, and you probably want it to be continued.
将 stderr 重定向到
/dev/null
。Redirect stderr to
/dev/null
.在python 3中,@Boaz Yaniv的答案可以简化,
因为python3中的每个类都是从
Object
继承的,所以从技术上讲这是可行的,至少我自己在python 3.6.5环境中尝试过。In python 3, @Boaz Yaniv's answer can be simplified as
since every class in python3 is inherited from
Object
, so technically this would work, at least I've tried it by myself in python 3.6.5 environment.这是一个更易读、更简洁的解决方案,用于处理可以安全忽略的错误,而不必求助于典型的 try/ except/pass 代码块。
Here is a more readable, succinct solution for handling errors that are safe to ignore, without having to resort to the typical try/except/pass code block.
有很多令人惊奇的答案,我最近有一个要求,我想抑制终端中打印的错误,并且还应该启用输入,我发现的最简单的方法如下。
There are a lot of amazing answers and I recently had a requirement that I want to suppress the error from printing in the terminal and also inputs should be enabled and the easiest way I found was below.