wim*_*wim 5 python import namespaces module ipython
在file1.py中:
def foo():
import file2
print "I'm the old file1.py"
file2.bar()
if __name__ == '__main__':
foo()
Run Code Online (Sandbox Code Playgroud)
在file2.py中
print "I'm the old file2.py"
def bar():
print "I'm in the old file2.bar()"
Run Code Online (Sandbox Code Playgroud)
在下面的交互式会话的第5行上,对file1.py和file2.py进行修改后,将单词的所有三个出现都更改old为new,new仍然不使用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()
Run Code Online (Sandbox Code Playgroud)
它从哪里获取file2.py中的旧代码?
我一定误会了一些东西,因为我认为(来自ipython帮助run):
该文件在最初仅由其组成
__name__ == '__main__'并sys.argv按照指示构造的名称空间中执行 。因此,它将环境看作是作为独立程序运行
我已经删除了.pyc文件,并且可以从命令whos中看到名称空间中不存在file2模块。但是,为什么第二次运行file1时不再次执行导入?
run文档中的注释解释道,它不会启动新的 Python 进程,而是在当前进程中执行代码——不是在当前命名空间中,而是在当前的 Python 进程中。因此,sys.modules仍然存在并且使用旧的缓存模块。(你熟悉Python正常情况下缓存导入模块的方式吗?)
要解决此问题,请每次都在新的 Python 进程中运行。reload这不仅仅是一个小问题,而且可能会导致我觉得不值得的头痛。