【发布时间】:2019-07-03 09:53:48
【问题描述】:
模块重载如何在 python 3.7.1 中工作?
设置和总结
我在 Linux 中运行 python 3.7.1。我正在开发一个 C 模块,一旦模块发生更改,重新加载模块会非常方便。我关注了How do I unload (reload) a Python module?,但我无法让它在这种环境中工作。
为了演示我的问题,我根据教程中的 SPAM 示例编写了一个简单的模块,该模块返回模块的构建时间。它永远不会重新加载。
代码
实现是教程中的垃圾邮件示例。它有一个函数 hello,它返回构建时间:
return Py_BuildValue("s", __TIME__);
我正在使用以下 python 脚本编译和加载:
import os
import helloworld
print(helloworld.hello('test'))
os.system("touch helloworld.c")
os.system("python3 setup.py build")
os.system("python3 setup.py install --user")
from importlib import reload
helloworld=reload(helloworld)
print(helloworld.hello('test'))
模块导入,触摸主文件,编译安装,然后重新加载。
输出
模块应该在重新加载后显示新的编译时间,但输出没有改变(我省略了一些调试消息,输出是第一行/最后一行,08:04:20):
python driver.py
08:04:20
running build
running build_ext
building 'helloworld' extension
gcc ...
running install
running build
running build_ext
running install_lib
copying build/lib.linux-x86_64-3.7/helloworld.cpython-37m-x86_64-linux-gnu.so -> /home/wuebbel/.local/lib/python3.7/site-packages
running install_egg_info
Removing /home/wuebbel/.local/lib/python3.7/site-packages/HelloWorld-2.1-py3.7.egg-info
Writing /home/wuebbel/.local/lib/python3.7/site-packages/HelloWorld-2.1-py3.7.egg-info
08:04:20
再次运行脚本会加载正确的模块并显示新时间:
wuebbel@02e267406db3:~/Projekte/Mandelbrot Demos/helloworld$ python driver.py
08:16:58
...
08:16:58
似乎我的模块永远不会重新加载。这样做的正确方法是什么?
【问题讨论】:
-
你可以试试
sys.modules.pop("helloworld"),然后重新加载 -
我想知道我提供的解决方法是否有效。根据我发布的其他链接,我对此表示怀疑