首页 > 解决方案 > 共享模块变量不更新?

问题描述

我试图在包和模块之间共享(设置/获取)一个变量,但值没有改变。

我究竟做错了什么?

共享.py

my_shared_value = 'init'

mod_write.py

import mylib.shared
mylib.shared.my_shared_value = 'changed'

mod_read.py

import mylib.shared

while True:
    # outputs always 'init' but should output 'changed' 
    # after mod_set.py was executed.
    print(mylib.shared.my_shared_value)

执行(相同的虚拟环境)

# Terminal 1
python ./mod_read.py # outputs 'init', runs forever

# Terminal 2
python ./mod_write.py # doesn't affect the output of Terminal 1

标签: pythonpython-3.xmodule

解决方案


要查看 mod_write.py 文件的结果,您还需要导入该文件(但在第一次导入之后)。

在您的情况下,您单独执行文件,因此您看不到预期的结果。

试试这个方法:

import mylib.shared
import mylib.mod_write

while True:
    # outputs always 'init' but should output 'changed' 
    # after mod_set.py was executed.
    print(mylib.shared.my_shared_value)

推荐阅读