我正在尝试编写一个脚本,每 10 秒更新一次全局变量。为简单起见,我们只需在教学时间时增加 q
import time, threading
q = 0
def f(q):
# get asset position every 10 seconds:
q += 1
print q
# call f() again in 10 seconds
threading.Timer(10, f).start()
# start calling f now and every 10 sec thereafter
f(q)
相反,Python 说:
UnboundLocalError: local variable 'q' referenced before assignment
更改变量q
的正确方法是什么?
此示例使用线程,不更新任何值。 Run certain code every n seconds
最佳答案
您需要显式地将 q 声明为全局变量。否则,q += 1
会使解释器感到困惑。
import threading
q = 0
def f():
global q
q += 1
print q
threading.Timer(10, f).start()
f()
关于python - 在Python中使用线程更改全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24900460/