使用Python urllib超时下载文件?

时间:2015-09-24 14:16:15

标签: python urllib2 urllib

Python初学者。如果进程耗时超过500秒,我希望能够暂停下载视频文件。

import urllib
try:
   urllib.urlretrieve ("http://www.videoURL.mp4", "filename.mp4")
except Exception as e:
   print("error")

如何修改我的代码以实现这一目标?

3 个答案:

答案 0 :(得分:11)

更好的方法是使用requests,以便您可以流式传输结果并轻松检查超时:

import requests

# Make the actual request, set the timeout for no data to 10 seconds and enable streaming responses so we don't have to keep the large files in memory
request = requests.get('http://www.videoURL.mp4', timeout=10, stream=True)

# Open the output file and make sure we write in binary mode
with open('filename.mp4', 'wb') as fh:
    # Walk through the request response in chunks of 1024 * 1024 bytes, so 1MiB
    for chunk in request.iter_content(1024 * 1024):
        # Write the chunk to the file
        fh.write(chunk)
        # Optionally we can check here if the download is taking too long

答案 1 :(得分:1)

urlretrieve没有该选项。但是你可以在urlopen的帮助下轻松地执行你的例子并将结果写在一个文件中,如下所示:

request = urllib.urlopen("http://www.videoURL.mp4", timeout=500)
with open("filename.mp4", 'wb') as f:
    try:
        f.write(request.read())
    except:
        print("error")

如果您使用的是Python 3.如果您使用的是Python 2,则应该使用urllib2。

答案 2 :(得分:0)

尽管urlretrieve不具有此功能,但仍可以为所有新套接字对象设置默认超时(以秒为单位)。

import socket
import urllib    

socket.setdefaulttimeout(15)

try:
   urllib.urlretrieve ("http://www.videoURL.mp4", "filename.mp4")
except Exception as e:
   print("error")