【问题标题】:urlopen with timeout fails behind proxy带有超时的 urlopen 在代理后面失败
【发布时间】:2014-04-26 16:53:18
【问题描述】:

linux下的python 2.7.3:尝试使用超时参数时出现奇怪的行为

from urllib2 import urlopen, Request, HTTPError, URLError

url = "http://speedtest.website-solution.net/speedtest/random350x350.jpg"

try:
    #f = urlopen(url, timeout=30)   #never works - always times out
    f = urlopen(url)    #always works fine, returns after < 2 secs
    print("opened")
    f.close()
    print("closed")

except IOError as e:
    print(e)
    pass

编辑:

深入研究,似乎级别较低..以下代码有同样的问题:

    s = socket.socket()
    s.settimeout(30)
    s.connect(("speedtest.website-solution.net", 80))    #times out
    print("opened socket")
    s.close()

它在 socks 代理后面运行。使用tsocks python test.py 运行。想知道这是否会因为某种原因搞砸套接字超时? timeout=None 工作正常,这似乎很奇怪。

【问题讨论】:

  • +1 表示简洁、完整的示例程序。调用urlopen,您的程序可以在我的PC 上完美运行。我有 Ubuntu 13.10,Python 2.7.5。您使用的是什么操作系统?
  • 没有好主意;当你说它总是超时时,它会在你指定的时间之后超时吗?如果设置 timeout(100) 需要 100 秒才能超时?
  • @TessellatingHeckler 是的 - 完全正确

标签: python proxy urlopen


【解决方案1】:

好的..想通了。这确实与代理有关。不知道为什么,但下面的代码似乎可以解决它:

来源:https://code.google.com/p/socksipy-branch/

把它放在代码的开头:

import urllib2
from urllib2 import urlopen, Request, HTTPError, URLError
import httplib

import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "192.168.56.1", 101)
socks.wrapmodule(urllib2)

现在一切正常..

【讨论】:

    猜你喜欢
    • 2011-07-04
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-11
    • 1970-01-01
    • 2012-07-17
    • 2012-07-31
    • 1970-01-01
    相关资源
    最近更新 更多