user225312 user225312 - 3 months ago 17
Python Question

Python ftplib and storbinary

Trying to understand how the


I am trying to save a file to a FTP server and implement a callback.

The documentation says:

FTP.storbinary(command, file[, blocksize, callback, rest])

function is defined as in the documentation:

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

How do I implement this callback? A sample callback on the
(reading a file) could look like:

def handle(block):
print ".",

Which will show the progress of the file being downloaded,
being the file object.

But I am at a loss on how to implement this with

Any suggestions on how this can be done? I know about the
parameter, but how do I adjust it with the uploading?


I have a callback for uploading as:

def handle(block):
print ".",

But as expected, it gives the error:

an integer is required

also doesn't work.


If your callback is

def handle(block):
    print ".", 

Python has first class functions that can be passed as params- this is the point of a callback- you you pass the function as param to the storbinary call-

ftp.storbinary(command="stor someFileNameOnServer", file=open("localFile",'rb'), callback=handle,blocksize=1024)

From the python doc,

callback is an optional single parameter callable that is called on each block of data after it is sent.

It's purely a post-processing method for e.g. showing transfer status, it's called after each block of data is sent. Above it would be called after sending every 1024 bytes of data.

To implement transfer status, something like this-

sizeWritten = 0
totalSize = someMethodToGetTotalBytesInFile()
def handle(block):
    global sizeWritten
    sizeWritten += 1024
    percentComplete = sizeWritten / totalSize
    print "%s percent complete" %str(sizeWritten / totalSize)

os.path.getsize will give you the total size in bytes of your file.