从循环中 运行 的第二个模块访问变量

Accessing a variable from a second module that run on a loop

y.py 脚本连续运行并更新 z 变量。我需要通过访问 z 变量 x.py,它不起作用。我正在尝试使用两个不同的线程。

y.py

import threading

# Run every 3 seconds to update the z variable
if __name__ == "__main__": # Should avoid the importation to modify the z variable content

    delay = 3
    z = 0

    def foo():
        global z
        z = z + 1
        print("inner",z)
        # This thread run continuously and should not 
        # block the other threads
        threading.Timer(delay,foo).start()  

    foo()
    print("outer",z + 10)

x.py

import y

foo = y.z
print(foo)

你需要改变你在y.py做事的方式:

import threading

# Run every 3 seconds to update the z variable
delay = 3
z = 0

def foo():
    global z
    z = z + 1
    print("inner",z)
    # This thread run continuously and should not
    # block the other threads
    threading.Timer(delay,foo).start()

foo()
print("outer",z + 10)

if __name__ == "__main__": # Should avoid the importation to modify the z variable content
    foo()

if __name__ == "__main__":是驱动代码Look here for more info

您应该使用它来调用函数,而不是在其中嵌套函数。

x.py更改为:

import y

foo = y
print(foo.z)

来自x.py的输出:

inner 1
outer 11
1
inner 2
inner 3
...

我已经稍微更改了您的代码以加快我回答它的速度,因此它可能无法产生您想要的输出,因此您可能需要更改它,但您的问题应该已解决。