简体   繁体   English

用Python中的线程更改全局变量

[英]changing global variable with thread in Python

I am trying to write a script updating a global variable every 10 seconds. 我试图编写一个脚本,每10秒更新一次全局变量。 For simplicity let's just increment q once teach time 为了简单起见,让我们一次教导时间就增加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)

Instead python says: 相反,python说:

UnboundLocalError: local variable 'q' referenced before assignment

What is the correct way to change the variable q ? 更改变量q的正确方法是什么?


this example uses threading, doesn't update any values. 本示例使用线程,不更新任何值。 Run certain code every n seconds 每n秒执行特定程式码

You need to explicitly declare q as a global. 您需要显式声明q为全局变量。 q += 1 confuses the interpreter otherwise. q += 1会使解释器混乱。

import threading

q = 0
def f():
    global q
    q += 1
    print q
    threading.Timer(10, f).start()

f()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM