gpt4 book ai didi

python - 在Python REPL中,如何从所有文件中获取最新代码?

转载 作者:太空宇宙 更新时间:2023-11-03 17:18:09 24 4
gpt4 key购买 nike

我在两个文件中有以下玩具代码:

文件b.py :

def test_b():
print "b"

文件a.py : 从 b 导入 test_b

def test_a():
print "a"
test_b()

然后我运行 python REPL:

>>> execfile("a.py")
>>> test_a()
a
b

然后我修改b.py进入: def test_b(): 打印“bb”

并在 REPL 中运行:

>>> execfile("b.py")
>>> test_a()
a
bb

目前一切都很好。现在我修改a.py进入:

from b import test_b

def test_a():
print "aa"
test_b()

现在我遇到了 REPL:

>>> execfile("a.py")
>>> test_a()
aa
b

自从 REPL 获得旧版本 b.py 以来,这已经不行了。 Python 在加载文件时似乎做了一些缓存,我的问题是:有没有办法强制它不这样做?我找不到该功能的正确选项 excefile

最佳答案

根据: https://docs.python.org/2/tutorial/modules.html您可以使用 reload(a) (之前必须已导入一次)。请参阅说明,这可能不是最佳解决方案。

引文:

Note

For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter – or, if it’s just one module you want to test interactively, use reload(), e.g. reload(modulename).

以及功能描述:https://docs.python.org/2/library/functions.html#reload适度使用,因为:

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.

最简单的解决方案是重新启动解释器。

关于python - 在Python REPL中,如何从所有文件中获取最新代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33439283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com