【发布时间】:2012-09-27 13:15:46
【问题描述】:
使用从 pprocess 调用的函数时,我似乎无法在 Python 中修改全局变量。这是我的例子:
import pprocess
import time
numbers=[0,0,0,0,0,0,0,0,0,0]
# find system time and store in global variable
def find_time(index):
global numbers
x=time.time()
print "Setting element %s of numbers to %f" % (index, x)
numbers[index]=x
return x
# parallel execution of the function
results=pprocess.pmap(find_time, [0,1,2,3,4,5,6,7,8,9], limit=6)
for y in results:
print '%f' % y
# this list is unchanged
print numbers
# serial execution of the function
for x in [0,1,2,3,4,5,6,7,8,9]:
find_time(x)
# now it seems to work
print numbers
"numbers" 只是一个零列表,为了演示,我尝试将每个列表元素设置为当前系统时间。当使用 pprocess 调用时,这不起作用,但是当我使用简单的 for 循环调用函数时,全局变量会发生变化。
我花了一些时间阅读有关全局变量的信息,并真诚地希望这不是一个小问题。谁能给我解释一下这是怎么回事?
非常感谢,
恩诺
【问题讨论】:
-
另请注意,此处不需要
global关键字。即使你没有将它定义为全局对象,Python 也会很高兴地改变一个全局对象。如果您通过赋值更改变量引用的对象,则只需要global。
标签: python function parallel-processing global-variables