python - 共享模块变量不更新?
问题描述
我试图在包和模块之间共享(设置/获取)一个变量,但值没有改变。
我究竟做错了什么?
共享.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
解决方案
要查看 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)
推荐阅读
- python - 将多个 PySpark 数据帧与 MergeSchema 合并
- google-cloud-firestore - 什么是 Cloud Firestore 存储数据配额?
- python - Python 中的 HTML 消息
- django - 在 Django CBV 中调用 DetailView 时,是否仍然可以在 has_permission 方法中获取当前对象
- angular - 角材料安装 +
- php - 如何使 php regex preg_replace 工作
- python - 按特定列对数据进行分组,然后将行值拆分为不同的列
- javascript - 在 Nodejs 中同时使用 Currying 和 Module.export
- excel - 为什么我的 Excel 公式只从范围中取一个值?
- java - MainActivity 无法强制转换为 android.app.TimePickerDialog$OnTimeSetListener 无法解决