You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在一个Python文件中定义变量并在其他py文件中调用更新后的值

问题根因

这是Python模块导入的变量作用域规则导致的:
使用from functions import *导入plc_variables时,会在main.py的当前作用域创建一个同名变量,初始和functions模块中的plc_variables指向同一个空字典。但get_plc_variables函数中通过global关键字修改的是functions模块自身作用域下的plc_variables,相当于给模块内的变量重新绑定了新的字典对象,而main.py里的同名变量还是指向原来的空字典,因此打印结果始终为空。


解决方案

方案1:通过模块名访问全局变量(最稳妥,推荐)

不要单独导入变量,而是导入整个functions模块,直接访问模块下的属性,永远能拿到最新值:

修改后的main.py代码

import time
import functions  # 导入整个模块,而非单独导入变量/函数

while True:
    functions.get_plc_variables()
    print(functions.plc_variables)  # 直接访问模块下的变量
    time.sleep(1)

其他文件需要使用该变量时,同样导入functions模块后访问functions.plc_variables即可。

方案2:修改原字典内容而非重新赋值

如果不想调整导入逻辑,可以修改get_plc_variables的实现,不重新给plc_variables赋值,而是清空原有字典后更新内容,保证两个作用域的变量始终指向同一个对象:

修改后的functions.py代码

plc_variables = {}
plc_variables_path = ".../plc_variables.txt"

def get_plc_variables():
    global plc_variables
    # 你的原计算逻辑,得到新的字典结果
    new_plc_vars = 这里替换为你原来的计算代码
    # 替换原有重新赋值的逻辑,改为更新已有的字典对象
    plc_variables.clear()
    plc_variables.update(new_plc_vars)

该方案下main.py的原有代码不需要修改,即可正常打印更新后的字典内容。


多线程场景额外注意事项

如果有多个线程同时读写plc_variables,需要加线程锁避免读写冲突,可参考如下改造:

import threading
plc_variables = {}
plc_lock = threading.Lock()
plc_variables_path = ".../plc_variables.txt"

def get_plc_variables():
    global plc_variables
    new_plc_vars = 你的计算逻辑
    # 写操作加锁
    with plc_lock:
        plc_variables.clear()
        plc_variables.update(new_plc_vars)

# 提供统一的读接口,避免读取过程中数据被修改
def read_plc_variables():
    with plc_lock:
        return plc_variables.copy()

内容的提问来源于stack exchange,提问作者Arian Sakhaei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 16:51:03