Python ftplib and storbinary

15,302

If your callback is

def handle(block):
    f.write(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.

Share:
15,302
user225312
Author by

user225312

Updated on June 28, 2022

Comments

  • user225312
    user225312 almost 2 years

    Trying to understand how the ftplib works.

    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])
    

    callback 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 block.

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

    def handle(block):
        f.write(block)
        print ".", 
    

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

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

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

    UPDATE:

    I have a callback for uploading as:

    def handle(block):
        f.read(block)
        print ".",
    

    But as expected, it gives the error:

    an integer is required

    Passing int(block) also doesn't work.