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

标签 python

我有这个命令

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/

相关文章:

python - : `if x.isupper() and not in y` 行语法错误

python - 如何在 Estimator 训练期间动态加载数据集的新部分?

python - 强制子类实现属性python

python - 使用 Python 3 将 JSON 转换为 CSV

python - 如何控制plt.quiver?

Python:for if-else 之间的循环,这是如何/为什么工作的?

python - 如何使用 Python 的 cElementTree 创建 <!DOCTYPE>

python - 如何在 Kivy 中通过 ids 正确链接按钮?

python - 破译 lambda 表达式

python - 通过 Lua 从 Redis 获取与键模式匹配的所有值