Skip to content Skip to sidebar Skip to footer

Python: Defining A Variable In Callback Function...not Sure Where

Excerpt: file = open('D:\\DownloadFolder\\test.mp3', 'wb') def callback(data): file.write(data) sizeWritten += len(data) print(sizeWritten) connect.retrbinary('RETR t

Solution 1:

If it is okay for sizeWritten to be a global (e.g. there is only ever going to be one callback active at a time), you can mark it as such in your function:

file = open("D:\\DownloadFolder\\test.mp3", "wb")
sizeWritten = 0defcallback(data):
    global sizeWritten
    file.write(data)
    sizeWritten += len(data)
    print(sizeWritten)

and any assignments to the name in callback alter the global.

In Python 3, you can also use a closure, and the nonlocal keyword:

defdownload(remote, local):
    file = open(local, "wb")
    sizeWritten = 0defcallback(data):
        nonlocal sizeWritten
        file.write(data)
        sizeWritten += len(data)
        print(sizeWritten)

    connect.retrbinary('RETR ' + remote, callback)
    print("completed")

This encapsulates the sizeWritten and file objects in a local namespace, at least.

However, you could get the same information directly from the open file file object:

def callback(data):
    file.write(data)
    print(file.tell())

Post a Comment for "Python: Defining A Variable In Callback Function...not Sure Where"