gpt4 book ai didi

python - 修改文件后,旧代码仍在 ipython 中执行

转载 作者:太空狗 更新时间:2023-10-30 01:23:59 27 4
gpt4 key购买 nike

在 file1.py 中:

def foo():
import file2
print "I'm the old file1.py"
file2.bar()

if __name__ == '__main__':
foo()

在 file2.py 中

print "I'm the old file2.py"

def bar():
print "I'm in the old file2.bar()"

在下面交互式 session 的第 5 行,在对 file1.py 和 file2.py 进行修改后,将出现的所有三个单词 old 更改为 newnew file2.py 中的代码仍然没有使用。

wim@wim-ubuntu:~/sandpit$ ipython
>>> run file1.py
I'm the old file2.py
I'm the old file1.py
I'm in the old file2.bar()
>>> !rm file2.pyc
>>> # modify file1, file2
>>> run file1.py
I'm the new file1.py
I'm in the old file2.bar()

它从哪里获取 file2.py 的旧代码?

我一定是误会了什么,因为我认为(来自 run 的 ipython 帮助):

The file is executed in a namespace initially consisting only of __name__ == '__main__' and sys.argv constructed as indicated. It thus sees its environment as if it were being run as a stand-alone program

我已经删除了 .pyc 文件,并且可以从命令 whos 中看到命名空间中不存在 file2 模块。但是为什么第二次运行file1时没有再次执行import呢?

最佳答案

run 不会启动新的 Python 进程,而是在当前进程中执行您的代码——不是在当前命名空间中,而是在当前 Python 进程中,文档中的注释解释道。因此,sys.modules 仍然存在,并使用旧的缓存模块。 (您是否熟悉 Python 通常缓存导入模块的方式?)

要解决此问题,请每次都在一个新的 Python 进程中运行。 reload 不仅仅是一个小问题,而且会导致我认为不值得的头痛。

关于python - 修改文件后,旧代码仍在 ipython 中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7418538/

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