Python:禁止从命令行转到错误? [英] Python: Suppressing errors from going to commandline?

查看:281
本文介绍了Python:禁止从命令行转到错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试从命令行执行一个python程序时,会出现以下错误。这些错误对我的输出不会造成任何问题。我不希望在命令行中显示

When I try to execute a python program from command line, it gives the following error. These errors do not cause any problem to my ouput. I dont want it to be displayed in the commandline

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

我如何抑制错误?

推荐答案

不抓住HTMLParseError为您工作?如果 test.py 是您的python文件的名称,它将传播到那里,所以应该。

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.

try:
    # Put parsing code here
except HTMLParseError:
    pass

您还可以通过重定向stderr来抑制错误消息为零,像Ignacio所说。要在代码中做到这一点,你可以写下列内容:

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:

import sys

class DevNull:
    def write(self, msg):
        pass

sys.stderr = DevNull()

但是,这可能不是你想要的,因为从你的错误看,脚本执行停止,你可能希望继续。

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.

这篇关于Python:禁止从命令行转到错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆