使用 Python urllib 超时文件下载? [英] Timeout a file download with Python urllib?
本文介绍了使用 Python urllib 超时文件下载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里是 Python 初学者.如果该过程花费的时间超过 500 秒,我希望能够使我的视频文件下载超时.
Python beginner here. I want to be able to timeout my download of a video file if the process takes longer than 500 seconds.
import urllib
try:
urllib.urlretrieve ("http://www.videoURL.mp4", "filename.mp4")
except Exception as e:
print("error")
我如何修改我的代码来实现这一点?
How do I amend my code to make that happen?
推荐答案
更好的方法是使用 requests
以便您可以流式传输结果并轻松检查超时:
Better way is to use requests
so you can stream the results and easily check for timeouts:
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
这篇关于使用 Python urllib 超时文件下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文