Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python urllib下载文件超时?_Python_Urllib2_Urllib - Fatal编程技术网

使用Python urllib下载文件超时?

使用Python urllib下载文件超时?,python,urllib2,urllib,Python,Urllib2,Urllib,这里是Python初学者。如果视频文件的下载过程超过500秒,我希望能够超时 import urllib try: urllib.urlretrieve ("http://www.videoURL.mp4", "filename.mp4") except Exception as e: print("error") 如何修改代码以实现此目的?urlretrieve没有该选项。但是,在urlopen的帮助下,您可以轻松地执行示例,并将结果写入文件,如下所示: request = ur

这里是Python初学者。如果视频文件的下载过程超过500秒,我希望能够超时

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

如何修改代码以实现此目的?

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")

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

更好的方法是使用
请求
,这样您就可以流式传输结果并轻松检查超时:

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

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

import socket
import urllib    

socket.setdefaulttimeout(15)

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

urlopen的可能复制可能很容易,但对于大型文件来说。Read .Read()可能会很慢,而且需要花费很长时间,你应该考虑在该函数周围添加一个超时,很可能使用SigalPACK。它不仅可以很慢,而且可能完全失败。例如,假设文件大小为10GB,无法放入内存。
还请注意,Python 3中的urllib.request.urlopen()函数相当于urllib2.urlopen(),并且urllib.urlopen()已被删除。
3.6中正确的调用是
urllib.request.urlopen()。我不知道是否有一个Python版本,其中
urllib.urlopen()
实际工作,所以我不会编辑答案。