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

问题描述:

我有两个.py脚本. script1.pyscript2.py

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

I am importing few variables from script2.py like:

from script2 import variable1 as var1

效果很好.

但是,当我在script2.py update variable1,然后重新运行script1.py时,variable1的更新未显示在script1.py中.为什么?

But when I update variable1 in script2.py, and then re-run script1.py, the update of variable1 doesn't show up in script1.py. Why is that so?

如果我完全关闭IPython,然后再次重新打开IPython,则会显示variable1的更新.但是我不想一直这样做,因为我只需要打开很少的地块即可.

The update of variable1 shows up if I close IPython completely and then re-open IPython again. But I don't want to do this all the time as I need few plot's to be open.

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

I am using IPython 1.2.1 and Python 2.7.6 (if further info maybe needed).

有一种重新加载模块的方法,尽管它似乎不适用于别名.您可以使用 reload(module_name) .正如您将看到的文档说明,您的别名将不会刷新:

There is a way to reload modules, though it doesn't seem to work well with aliasing. You can use reload(module_name). As you'll see the docs note that your aliases wont be refreshed:

如果一个模块使用from ... import ...从另一个模块导入对象,则对另一个模块调用reload()不会重新定义 从其中导入的对象-解决此问题的一种方法是重新执行 from语句,另一种是使用导入名称和限定名称 (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

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

You could still alias, but you'd need to refresh the aliased names each time:

import script2
var1 = script2.variable1

...

reload(script2)
var1 = script2.variable1

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

If you didn't do this, var1 would hold the old value.

但是,如果您认为有必要(并且经常发生),可以立即执行所有操作

You could however have a quick function to do this all at once if you think it's necessary (and if it is happening often)

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

注意,我在这里使用global,以便在全局命名空间中修改var1,而不仅仅是在该函数中声明.如果您确实只有一个值,则可以使用return var1,但是我认为这是一种罕见的情况,其中global更好.

Note I use global here so that var1 is modified in the global namespace, not just declared in that function. If you really only have one value you could use return var1, but I think this is a rare case where global is better.