在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()"
在下面的交互式会话的第5行,在对file1.py和file2.py进行修改后,将旧单词的所有三次出现更改为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()
从file2.py获取旧代码从哪里来?
我必须误解一些东西,因为我想(从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文件,可以从命令中看到命名空间中没有file2模块.但是为什么第二次运行file1时导入不再执行?
解决方法:
run不会启动新的Python进程,而是执行当前的代码 – 而不是当前的命名空间,但在当前的Python进程中,文档中的说明解释了.因此,sys.modules仍然存在,并使用旧的缓存模块. (你熟悉Python通常导入模块的方式吗?)
要解决此问题,请每次都在新的Python进程中运行.重新加载不仅仅是一个小问题,并且可能导致我发现不值得的头痛.
标签:python,import,module,namespaces,ipython
来源: https://codeday.me/bug/20190630/1337249.html