Python FTP“chunk”迭代器(不将整个文件加载到内存中)

时间:2016-04-29 15:51:54

标签: python ftp

关于检索FTP文件并将其写入流(例如字符串缓冲区或文件然后可以迭代)的堆栈溢出有几个答案。

例如:Read a file in buffer from FTP python

但是,这些解决方案涉及在开始处理内容之前将整个文件加载到内存中或将其下载到磁盘。

我没有足够的内存来缓冲整个文件而我无法访问磁盘。这可以通过处理回调函数中的数据来完成,但是我想知道是否可以将ftp代码包装在一些返回迭代器的魔法中,而不是用回调来代替我的代码。

即。而不是:

def get_ftp_data(handle_chunk):
    ...
    ftp.login('uesr', 'password') # authentication required
    ftp.retrbinary('RETR etc', handle_chunk)
    ...

get_ftp_data(do_stuff_to_chunk)

我想:

for chunk in get_ftp_data():
    do_stuff_to_chunk(chunk)

并且(与现有答案不同)我希望在迭代之前不将整个ftp文件写入磁盘或内存。

1 个答案:

答案 0 :(得分:4)

您必须将retrbinary调用放在另一个线程中,并将回调源块放到迭代器中:

import threading, Queue

def ftp_chunk_iterator(FTP, command):
    # Set maxsize to limit the number of chunks kept in memory at once.
    queue = Queue.Queue(maxsize=some_appropriate_size)

    def ftp_thread_target():
        FTP.retrbinary(command, callback=queue.put)
        queue.put(None)

    ftp_thread = threading.Thread(target=ftp_thread_target)
    ftp_thread.start()

    while True:
        chunk = queue.get()
        if chunk is not None:
            yield chunk
        else:
            return

如果您不能使用线程,那么您可以做的最好就是将回调写为协程:

from contextlib import closing


def process_chunks():
    while True:
        try:
            chunk = yield
        except GeneratorExit:
            finish_up()
            return
        else:
            do_whatever_with(chunk)

with closing(process_chunks()) as coroutine:

    # Get the coroutine to the first yield
    coroutine.next()

    FTP.retrbinary(command, callback=coroutine.send)
# coroutine.close() #  called by exiting the block