Python初学者在这里。如果该过程花费的时间超过500秒,我希望能够使我的视频文件下载超时。
import urllib
try:
urllib.urlretrieve ("http://www.videoURL.mp4", "filename.mp4")
except Exception as e:
print("error")
我如何修改代码以实现这一目标?
更好的方法是使用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
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 socket
import urllib
socket.setdefaulttimeout(15)
try:
urllib.urlretrieve ("http://www.videoURL.mp4", "filename.mp4")
except Exception as e:
print("error")