Skip to main content
 首页 » 编程设计

python之从另一个脚本导入变量并保持更新

2025年05月04日33落叶

我有两个 .py 脚本。 script1.py 和 script2.py

我正在从 script2.py 中导入一些变量,例如:

from script2 import variable1 as var1 

效果很好。

但是当我更新 script2.py 中的variable1,然后重新运行script1.py 时, variable1 的更新没有出现在 script1.py 中。为什么会这样?

variable1 的更新会在我完全关闭 IPython 然后重新打开 IPython 时出现。但我不想一直这样做,因为我需要打开的情节很少。

我正在使用 IPython 1.2.1 和 Python 2.7.6(如果可能需要更多信息)。

请您参考如下方法:

有一种方法可以重新加载模块,但它似乎不能很好地处理别名。您可以使用 reload(module_name) .正如您将在文档中看到的那样,您的别名不会被刷新:

If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.

它建议使用

import script2  
script2.variable1 

您仍然可以使用别名,但每次都需要刷新别名:

import script2 
var1 = script2.variable1 
 
... 
 
reload(script2) 
var1 = script2.variable1 

如果您不这样做,var1 将保留旧值。

但是,如果您认为有必要(并且经常发生),您可以使用快速功能一次性完成所有这些操作

def reload_script2(): 
    global var1 
    reload(script2) 
    var1 = script2.variable1 

请注意,我在这里使用了 global,这样 var1 在全局命名空间中被修改,而不仅仅是在该函数中声明。如果你真的只有一个值,你可以使用 return var1,但我认为这是一种罕见的情况,global 更好。