[英]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 test.mp3', callback)
print("completed")
Python obviously complains that I didn't define sizeWritten
, but I'm not sure where I should define it. Python显然抱怨我没有定义
sizeWritten
,但是我不确定应该在哪里定义它。 If I put sizeWritten = 0
before the function it still gives an error local variable 'sizeWritten referenced before assignment
. 如果我在函数前放置
sizeWritten = 0
,它仍然会给出一个错误的local variable 'sizeWritten referenced before assignment
。 How should I do this? 我应该怎么做?
If it is okay for sizeWritten
to be a global (eg there is only ever going to be one callback active at a time), you can mark it as such in your function: 如果
sizeWritten
可以是全局的(例如,一次只能有一个回调活动),则可以在函数中将其标记为:
file = open("D:\\DownloadFolder\\test.mp3", "wb")
sizeWritten = 0
def callback(data):
global sizeWritten
file.write(data)
sizeWritten += len(data)
print(sizeWritten)
and any assignments to the name in callback
alter the global. callback
对该名称的任何分配都会更改全局名称。
In Python 3, you can also use a closure, and the nonlocal
keyword: 在Python 3中,您还可以使用闭包和
nonlocal
关键字:
def download(remote, local):
file = open(local, "wb")
sizeWritten = 0
def callback(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. 至少将
sizeWritten
和file
对象封装在本地名称空间中。
However, you could get the same information directly from the open file
file object: 但是,您可以直接从打开
file
file对象获得相同的信息:
def callback(data):
file.write(data)
print(file.tell())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.