【问题标题】:urllib2.urlopen timeout works only when connected to Interneturllib2.urlopen 超时仅在连接到 Internet 时有效
【发布时间】:2018-03-26 19:34:46
【问题描述】:

我正在编写 Python 2.7 代码以使用 urllib2 库从 HTML 页面读取值。 我想在 5 秒后超时 urllib2.urlopen 函数,以防万一没有互联网并跳转到剩余代码。

当计算机连接到有效的互联网连接时,它可以正常工作。为了测试我是否设置了timeout=0.1,它突然超时而没有打开网址,正如预期的那样。 但是当没有互联网时,超时不起作用我将超时设置为 0.1、5 或任何其他值。它根本不会超时。

这是我的代码:

import urllib2
url = "https://alfahd.witorbit.net/fingerprint.php?n"
try:
    response = urllib2.urlopen(url , timeout=5).read()
    print response 
except Exception as e:
    print e

连接到 Internet 时的结果,超时值为 5:

180

连接到 Internet 时的结果,超时值为 0.1:

<urlopen error timed out>

似乎超时工作。

NOT 连接到 Internet 并且具有任何超时值时的结果(尽管我为 timeout= 设置了任何值,但每次打开 url 时它都会在大约 40 秒后超时:

<urlopen error [Errno -3] Temporary failure in name resolution>

如果没有 Internet 连接,我如何使 urllib2.urlopen 超时?我错过了什么吗?请指导我解决这个问题。谢谢!

【问题讨论】:

  • 在请求之前发生名称解析失败,所以我的猜测是名称解析不是超时的主题。您可以通过在 /etc/hosts 文件中手动将名称解析为其 IP 来避免这种情况。然后你的超时应该像预期的那样运行。
  • 我现在打开了 'sudo nano /etc/hosts' 如何在 etc/hosts 中为 IP 添加名称,例如我给定的 url?我应该在这个文件中写什么?
  • 你在文件中写一个以主机IP地址开头的新行。然后是选项卡(或其他空格),然后是您要解析为该 IP 的主机名。例如10.10.10.10 alfahd.witorbit.net(将10.10....替换为实际IP)。请参阅来自 ask ubuntu 的 this question
  • 是的,这个解决方案对我有用。非常感谢..!

标签: python python-2.7 timeout urllib2 raspbian


【解决方案1】:

由于名称解析发生在发出请求之前,因此不受超时限制。您可以通过在 /etc/hosts 文件中提供主机 IP 来防止名称解析中出现此错误。例如,如果主机是subdomain.example.com,IP 是10.10.10.10,您可以在/etc/hosts 文件中添加以下行

10.10.10.10    subdomain.example.com

或者,您也可以直接使用 IP 地址,但是,某些网络服务器要求您使用主机名,在这种情况下,您需要修改 hosts 文件以离线使用该名称。

【讨论】:

    猜你喜欢
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 2010-09-17
    • 2012-03-07
    • 1970-01-01
    • 2013-04-07
    相关资源
    最近更新 更多