Sardathrion Sardathrion - 1 year ago 89
Python Question

Python's ftplib with tdqm

I have a console script which uses ftplib as a backend to get a number of files from an ftp server. I would like to use tqdm to give the user some feedback provided they have a "verbose" switch on. This must be optional as some users might use the script without


The ftplib's
method takes a callback so it should be possible to hook tqdm in there somehow. However, I have no idea what this callback would look like.

Answer Source

From FTP.retrbinary:

The callback function is called for each block of data received, with a single string argument giving the data block.

So the callback could be something like:

with open(filename, 'wb') as fd:
    total = ftpclient.size(filename)

    with tqdm(total=total) as pbar:
        def cb(data):
            l = len(data)

    ftpclient.retrbinary('RETR {}'.format(filename), cb)

Beware: This code is untested and probably has to be adapted.