[英]Python reload, and IPython autoreload as well, is not working
I am using Python + IPython for Data Science.我正在使用 Python + IPython 进行数据科学。 I made a folder that contains all the modules I wrote, organised in packages, something like
我创建了一个文件夹,其中包含我编写的所有模块,以包的形式组织,例如
python_workfolder
|
|---a
| |---__init__.py
| |---a1.py
| |---a2.py
|
|---b
| |---__init__.py
| |---b1.py
| |---b2.py
|
|---c
| |---__init__.py
| |---c1.py
| |---c2.py
|
|
|---script1.py
|---script2.py
At the beginning of each session I ask IPython to autoreload modules:在每个会话开始时,我要求 IPython 自动重新加载模块:
%load_ext autoreload
%autoreload 2
Now... let's say a1.py contains a class, A1
, that I want to call from one of the scripts.现在...假设 a1.py 包含一个类
A1
,我想从其中一个脚本调用它。 In the __init__.p
of package a
I import the module在包
a
的__init__.p
中导入模块
import a1
Then in the script I import the class I need然后在脚本中我导入我需要的类
from a.a1 import A1
If there is some error in class A1 and I modify it, there is no way to have Python reload it without restarting the kernel.如果类 A1 中存在一些错误并且我对其进行了修改,则无法在不重新启动内核的情况下让 Python 重新加载它。
I tried with del a1
, del sys.modules['a1']
, del sys.modules['a']
.我试过
del a1
, del sys.modules['a1']
, del sys.modules['a']
。 Each time it uses the old version of the class until I don't restart the kernel... anyone can give me some suggestions?每次它都使用旧版本的类,直到我不重新启动内核......任何人都可以给我一些建议吗?
This is funny.这很有趣。 It seems that my problem is not due to IPython but to Pyzo (the IDE I'm using).
看来我的问题不是由于 IPython 而是 Pyzo(我正在使用的 IDE)。 I added a TestClass to a1:
我向 a1 添加了一个 TestClass:
class TestClass:
def __init__(self):
pass
def disp(self):
print('AAA')
This is the output I get from running the commands in an IPython shell:这是我在 IPython shell 中运行命令得到的输出:
In [2]: from a.a1 import TestClass
In [3]: t=TestClass()
In [4]: t.disp()
AAA
Now I modify disp
to print 'BBB'现在我修改
disp
以打印“BBB”
In [5]: t.disp()
BBB
So it was actually reloaded... also because if I skip running the autoreload commands at the beginning, it prints 'AAA' again.所以它实际上被重新加载了......也是因为如果我在开始时跳过运行 autoreload 命令,它会再次打印“AAA”。 So it's working.
所以它的工作。
Instead if I run the commands through Pyzo (create a script, select the lines and press F9 or right click on the editor tab and select 'Run file') it doesn't get reloaded!相反,如果我通过 Pyzo 运行命令(创建脚本,选择行并按 F9 或右键单击编辑器选项卡并选择“运行文件”),它不会重新加载!
In [2]: (executing lines 1 to 3 of "testscript.py")
AAA
Again I modify disp
to print 'BBB'我再次修改
disp
以打印“BBB”
In [3]: (executing lines 1 to 3 of "testscript.py")
AAA
Old thread, but I had the same problem, so here is the solution I found.旧线程,但我遇到了同样的问题,所以这是我找到的解决方案。 You have to use the module
sys
and before importing a1
write the following sys.modules.pop('a1')
:您必须使用模块
sys
并在导入a1
之前编写以下sys.modules.pop('a1')
:
import sys
sys.modules.pop('a1')
import a1
The module is then reloaded.然后重新加载模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.