在上传过程中增加回调变量(Increment variable in callback during upload)

编程入门 行业动态 更新时间:2024-10-11 05:24:47
在上传过程中增加回调变量(Increment variable in callback during upload)

我有以下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.

更多推荐

本文发布于:2023-07-27 15:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1292339.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调   变量   过程中   上传   callback

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!