简体   繁体   English

Python:如果文件下载太大,则终止文件下载

[英]Python: Terminating a file download if it is too large

The size of a file on a remote server is usually reported by the content-length header, however it is unreliable. 远程服务器上文件的大小通常由content-length标头报告,但是不可靠。 Sometimes it is missing and occasionally it is misreported. 有时它会丢失,有时会被误报。 I don't want to exclusively rely on this header to determine whether my code should download a URL. 我不想完全依赖此标头来确定我的代码是否应该下载URL。

Is there a way to monitor the size of the file as it is downloaded and terminate the download if it exceeds a maximum size? 有什么方法可以监视文件下载时的大小,如果文件超过最大大小则终止下载?

What you can do is read the max file size you want and then check whether there are more bytes to be read by doing one more read. 您可以做的是读取所需的最大文件大小,然后通过再读取一次来检查是否还有更多字节要读取。 Like this: 像这样:

resp = urllib2.urlopen('http://www.google.com')
file_read = resp.read(max_wanted_size)
if resp.read(1) != '':
    #file is bigger than expected code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM