Skip to main content
 首页 » 编程设计

python之检查 command 在 Python 中是否有问题

2025年05月04日10落叶无声

我有这个命令

h = urllib.urlopen("http://google.com/") 

我如何检查它是否为我检索了一些错误、网络中断或我不希望发生的事情?

例如,类似的东西

如果错误 打印“错误”

谢谢

请您参考如下方法:

urllib.urlopen 已弃用,因为它已在 Python 3.0 中删除。使用 urllib2.urlopen相反,在文档中它说:

Raises URLError on errors.

也一样:

try: 
    h = urllib2.urlopen("http://google.com/") 
except urllib2.URLError as e: 
    # do something with the exception e.g. 
    print 'Error:', e.reason 

或者只是一条(无意义的)错误信息:

try: 
    h = urllib2.urlopen("http://google.com/") 
except urllib2.URLError: 
    print 'An error occurred.' 

URLError:

exception urllib2.URLError

The handlers raise this exception (or derived exceptions) when they run into a problem. It is a subclass of IOError.

reason
The reason for this error. It can be a message string or another exception instance (socket.error for remote URLs, OSError for local URLs).


您可能想阅读有关 Errors and Exceptions 的内容.