C语言回调函数访问全局变量,如何从回调函数访问(和编辑)变量?

我使用Boto访问Amazon S3.对于文件上传,我可以分配一个回调函数.问题是我无法从该回调函数访问所需的变量,直到我将它们设为全局变量.另一方面,如果我将它们设置为全局,那么它们也是所有其他Celery任务的全局(直到我重新启动Celery),因为文件上载是从Celery任务执行的.

这是一个上传JSON文件的函数,其中包含有关视频转换进度的信息.

def upload_json():

global current_frame

global path_to_progress_file

global bucket

json_file = Key(bucket)

json_file.key = path_to_progress_file

json_file.set_contents_from_string('{"progress": "%s"}' % current_frame,

cb=json_upload_callback, num_cb=2, policy="public-read")

这里有2个回调函数,用于上传视频转换过程中ffmpeg生成的帧和带有进度信息的JSON文件.

# Callback functions that are called by get_contents_to_filename.

# The first argument is representing the number of bytes that have

# been successfully transmitted from S3 and the second is representing

# the total number of bytes that need to be transmitted.

def frame_upload_callback(transmitted, to_transmit):

if transmitted == to_transmit:

upload_json()

def json_upload_callback(transmitted, to_transmit):

global uploading_frame

if transmitted == to_transmit:

print "Frame uploading finished"

uploading_frame = False

从理论上讲,我可以将uploaded_frame变量传递给upload_json函数,但它不会到达由Boto执行的json_upload_callback.

事实上,我可以写这样的东西.

In [1]: def make_function(message):

...: def function():

...: print message

...: return function

...:

In [2]: hello_function = make_function("hello")

In [3]: hello_function

Out[3]:

In [4]: hello_function()

hello

但是,这不允许您编辑函数中的值,只是让您读取值.

def myfunc():

stuff = 17

def lfun(arg):

print "got arg", arg, "and stuff is", stuff

return lfun

my_function = myfunc()

my_function("hello")

这有效.

def myfunc():

stuff = 17

def lfun(arg):

print "got arg", arg, "and stuff is", stuff

stuff += 1

return lfun

my_function = myfunc()

my_function("hello")

这给出了一个UnboundLocalError:在赋值之前引用的局部变量'stuff'.

谢谢.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值