使用请求在python中下载大文件

问题描述 投票:307回答:4

Requests是一个非常好的图书馆。我想用它来下载大文件(> 1GB)。问题是不可能将整个文件保存在内存中我需要以块的形式读取它。这是以下代码的问题

import requests

def DownloadFile(url)
    local_filename = url.split('/')[-1]
    r = requests.get(url)
    f = open(local_filename, 'wb')
    for chunk in r.iter_content(chunk_size=512 * 1024): 
        if chunk: # filter out keep-alive new chunks
            f.write(chunk)
    f.close()
    return 

由于某种原因它不起作用。在将其保存到文件之前,它仍会将响应加载到内存中。

UPDATE

如果你需要一个可以从FTP下载大文件的小客户端(Python 2.x /3.x),你可以找到它here。它支持多线程和重新连接(它确实监视连接),它还为下载任务调整套接字参数。

python download stream python-requests
4个回答
552
投票

使用以下流代码,无论下载文件的大小如何,Python内存使用都受到限制:

def download_file(url):
    local_filename = url.split('/')[-1]
    # NOTE the stream=True parameter below
    with requests.get(url, stream=True) as r:
        r.raise_for_status()
        with open(local_filename, 'wb') as f:
            for chunk in r.iter_content(chunk_size=8192): 
                if chunk: # filter out keep-alive new chunks
                    f.write(chunk)
                    # f.flush()
    return local_filename

请注意,使用iter_content返回的字节数不完全是chunk_size;它应该是一个通常更大的随机数,并且预计在每次迭代中都会有所不同。

请参阅http://docs.python-requests.org/en/latest/user/advanced/#body-content-workflow以获得进一步的参考。


189
投票

如果你使用Response.rawshutil.copyfileobj()会容易得多:

import requests
import shutil

def download_file(url):
    local_filename = url.split('/')[-1]
    with requests.get(url, stream=True) as r:
        with open(local_filename, 'wb') as f:
            shutil.copyfileobj(r.raw, f)

    return local_filename

这会将文件流式传输到磁盘而不会占用过多内存,代码很简单。


40
投票

您的块大小可能太大,您是否尝试删除它 - 可能一次只有1024个字节? (另外,你可以使用with来整理语法)

def DownloadFile(url):
    local_filename = url.split('/')[-1]
    r = requests.get(url)
    with open(local_filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024): 
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)
    return 

顺便提一下,你如何推断​​响应已被加载到内存中?

听起来好像python没有将数据刷新到文件,从其他SO questions你可以尝试f.flush()os.fsync()来强制文件写入和释放内存;

    with open(local_filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024): 
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)
                f.flush()
                os.fsync(f.fileno())

40
投票

不完全是OP所要求的,但是......用urllib做到这一点非常容易:

from urllib.request import urlretrieve
url = 'http://mirror.pnl.gov/releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso'
dst = 'ubuntu-16.04.2-desktop-amd64.iso'
urlretrieve(url, dst)

或者这样,如果要将其保存到临时文件:

from urllib.request import urlopen
from shutil import copyfileobj
from tempfile import NamedTemporaryFile
url = 'http://mirror.pnl.gov/releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso'
with urlopen(url) as fsrc, NamedTemporaryFile(delete=False) as fdst:
    copyfileobj(fsrc, fdst)

我看了看这个过程:

watch 'ps -p 18647 -o pid,ppid,pmem,rsz,vsz,comm,args; ls -al *.iso'

我看到文件正在增长,但内存使用率保持在17 MB。我错过了什么吗?

© www.soinside.com 2019 - 2024. All rights reserved.