python - 在Python中使用线程更改全局变量

标签 python python-2.7 timer python-multithreading

我正在尝试编写一个脚本,每 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/

相关文章:

python - numpy/核心/multiarray.so : undefined symbol: _Py_ZeroStruct

javascript - ionic : $timeout action is being executed even if it is cancelled

JAVA : How do I reduce the timer's time when the timer is running?

python - python脚本中开始保存rx二进制文件的时间?

python标准输入eof

python - 如何限制 Enthought 特征模块中 Float 特征的值?

java - 在 Android 中实现计时器 请参阅下面的代码以获取帮助

BLAST比对算法的Python实现?

python - 线程 Thread-4 中的异常 - 查找原因或捕获异常

sql - 在 python 中防止 SQL 注入(inject)