ipython文件每次打开重新运行吗_修改文件后,旧代码仍在ipython中执行

当在ipython环境中修改并重新运行file1.py时,虽然file1.py更新了,但file2.py的旧代码仍然被执行。即使删除了.pyc文件,第二次运行file1.py时,sys.modules中仍保留旧的file2模块。原因是run命令并不启动新的Python进程,而是直接执行当前进程中的代码。解决方法是确保每次都在新的Python进程中运行,以避免模块缓存导致的问题。
摘要由CSDN通过智能技术生成

在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值