python - 在 Windows 上的 Python 2.5 中下载时出现 urlopen 错误 10045、 'address already in use'

标签 python windows http download urllib2

我正在编写可在 Linux、OS X 和 Windows 上运行的代码。它从服务器下载一个包含大约 55,000 个文件的列表,然后遍历文件列表,检查文件是否存在于本地。 (通过 SHA 哈希验证和其他一些好东西。)如果文件不在本地或哈希不匹配,它会下载它们。

服务器端是 Ubuntu 上的普通 Apache 2,端口为 80。

客户端在 Mac 和 Linux 上完美运行,但在下载大量文件后在 Windows(XP 和 Vista)上出现此错误:

urllib2.URLError: <urlopen error <10048, 'Address already in use'>>

此链接:http://bytes.com/topic/python/answers/530949-client-side-tcp-socket-receiving-address-already-use-upon-connect指出 TCP 端口耗尽,但“netstat -n”从未向我显示超过六个处于“TIME_WAIT”状态的连接,甚至在它出错之前也是如此。

代码(为它下载的 55,000 个文件中的每一个调用一次)是这样的:

request = urllib2.Request(file_remote_path)
opener = urllib2.build_opener()
datastream = opener.open(request)
outfileobj = open(temp_file_path, 'wb')
try:
    while True:
        chunk = datastream.read(CHUNK_SIZE)
        if chunk == '':
            break
        else:
            outfileobj.write(chunk)
finally:
    outfileobj = outfileobj.close()
    datastream.close()

更新:我通过 greping 日志发现它进入下载例程正好 3998 次。我已经运行了多次,但每次都在 3998 时失败。鉴于链接文章指出可用端口为 5000-1025=3975(有些可能已过期并被重用),它开始看起来更像是链接文章描述的真正问题。但是,我仍然不确定如何解决这个问题。无法进行注册表编辑。

最佳答案

如果真的是资源问题(释放os socket资源)

试试这个:

request = urllib2.Request(file_remote_path)
opener = urllib2.build_opener()

retry = 3 # 3 tries
while retry :
    try :
        datastream = opener.open(request)
    except urllib2.URLError, ue:
        if ue.reason.find('10048') > -1 :
            if retry :
                retry -= 1
            else :
                raise urllib2.URLError("Address already in use / retries exhausted")
        else :
            retry = 0
    if datastream :
        retry = 0

outfileobj = open(temp_file_path, 'wb')
try:
    while True:
        chunk = datastream.read(CHUNK_SIZE)
        if chunk == '':
            break
        else:
            outfileobj.write(chunk)
finally:
    outfileobj = outfileobj.close()
    datastream.close()

如果你愿意,你可以插入一个 sleep 或者你让它取决于操作系统

在我的 win-xp 上问题没有出现(我达到了 5000 次下载)

我用 process hacker 观察我的进程和网络.

关于python - 在 Windows 上的 Python 2.5 中下载时出现 urlopen 错误 10045、 'address already in use',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1512057/

相关文章:

JavaScript getComputedStyle 不适用于颜色名称?

java - pkcs11 sso(使用之前的 windows 登录和智能卡)

python - 如何检查请求帖子是否已成功发布?

python - 谷歌地理编码 : points of interest within a specified radius

python - 右键单击 QPushButton 上的 contextMenu

python - VS代码中的文件夹

c# - 我如何忽略错误以继续执行C#代码中的项目?

python - 我很难从我的 python 程序上传数据到地下天气

python - 使用 python3 的异步 http 请求

Python httplib.HTTPS连接和密码