我有这个命令
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 的内容.
关于python - 检查 command 在 Python 中是否有问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2745968/