我有以下python脚本需要显示完成百分比的上传。 我无法增加追踪传输数据量的变量。 我得到一个 UnboundLocalError:赋值之前引用的局部变量'intProgress' 错误。 然而,如果我尝试打印这个变量,它打印的很好,所以它似乎被引用。
import os, sys, ftplib pathname = 'C:/Paradigm1/1.PNG' intFileSize = os.path.getsize(pathname) intPercentDone = 0 intProgress = 0 def callback(p): intProgress = intProgress + 1024 ##sys.stdout.write(str(intProgress)) sys.stdout.write("-") session = ftplib.FTP('Server','UserName','Password') f = open(pathname,'rb')# file to send session.storbinary('STOR /Ftp Accounts/PublicDownloads/test.png', f, 1024, callback) f.close()I have the following python script for an upload that needs to show percent done. I am having trouble incrementing the variable that tracks the amount of data transferred. I get an UnboundLocalError: local variable 'intProgress' referenced before assignment error. Yet if I try to print this variable it prints fine so it seems that it is referenced.
import os, sys, ftplib pathname = 'C:/Paradigm1/1.PNG' intFileSize = os.path.getsize(pathname) intPercentDone = 0 intProgress = 0 def callback(p): intProgress = intProgress + 1024 ##sys.stdout.write(str(intProgress)) sys.stdout.write("-") session = ftplib.FTP('Server','UserName','Password') f = open(pathname,'rb')# file to send session.storbinary('STOR /Ftp Accounts/PublicDownloads/test.png', f, 1024, callback) f.close()最满意答案
如果你想让callback()函数改变全局变量intProgress ,你必须在函数中声明它为global变量...
def callback(p): global intProgress intProgress = intProgress + 1024 ##sys.stdout.write(str(intProgress)) sys.stdout.write("-")...否则它会假设intProgress是一个局部变量,并且因设置它时尝试引用它而引起混淆。
If you want the callback() function to change the global variable intProgress, you have to declare it as global in the function...
def callback(p): global intProgress intProgress = intProgress + 1024 ##sys.stdout.write(str(intProgress)) sys.stdout.write("-")...otherwise it'll assume intProgress is a local variable, and get confused by the fact that you're trying to reference it when setting it.
更多推荐
发布评论