在python中进行异常处理时检查条件

时间:2014-07-01 07:53:00

标签: python exception if-statement exception-handling conditional-statements

这是我在python中的代码的一部分。我想查看错误消息,如果HTTPError(),那么我想将主机添加到ok.txt文件中。但它不起作用。这有什么问题?

except urllib2.URLError, e:
        print '%-15s\t%15r' % (url.strip(), e)
        if e == 'HTTPError()':
            OK.write('%-15s' % (url.strip()) + '\n')
            OK.flush()

当我运行整个脚本时,输出是这样的:

http://a.com        HTTPError()
http://b.com    URLError(timeout('timed out',),)
http://c.com    URLError(timeout('timed out',),)
http://d.com    URLError(error(111, 'Connection refused'),)
http://e.com           200

1 个答案:

答案 0 :(得分:3)

使用isinstance()检查您的错误是否为HTTPError类型:

except urllib2.URLError as e: # use the "as e" instead of the old style comma delimitation.
    print '%-15s\t%15r' % (url.strip(), e)
    if isinstance(e, HTTPError):
        OK.write('%-15s' % (url.strip()) + '\n')
        OK.flush()