如何reload模块在python3.7工作?

问题描述 投票:2回答:1

How does module reload work in python 3.7.1?

Setup and Summary

我在Linux上运行的Python 3.7.1。我正在开发一个C模块,一旦改变了这将是非常方便的重新加载模块。我跟着How do I unload (reload) a Python module?,但我不能让它在这种环境下工作。

对于我的问题的演示,我写了基于该返回模块的编译时间教程中的垃圾邮件例如一个简单的模块。它永远不会得到重新加载。

Code

实施是从教程垃圾邮件的例子。它有一个功能招呼它返回的编译时间:

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'))

该模块是进口的,主要的文件被触摸,它被编译并安装,然后重新加载。

Output

该模块应显示重装后的新的编译时间,但输出不会改变(我留下了一些调试消息,输出是第一/最后一行,8点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

看来,我的模块永远不会被加载。什么是这样做的正确方法是什么?

python module reload
1个回答
0
投票

我对重装包含编译的代码的模块,读取此答案的feasability疑惑:https://stackoverflow.com/a/48814213/6451573这表明PEP 489改变模块重新加载(蟒3.6和3.7之间),可能“断裂”共享库重新加载。

由于在共享库加载(dlopen的两者上POSIX和LoadModuleEx在Windows上)的限制,它通常是不可能的它已经在磁盘上的改变之后加载修改的库。

这可以解释你所遇到的问题。

如果这是一个操作的情况下,我建议你具有创建包的主Python程序,然后使用单独的Python进程加载它。

sub pro国.朋友:

import helloworld
print(helloworld.hello('test'))

master.朋友

import os,subprocess,sys
def runit():
   subprocess.run([sys.executable,os.path.join(os.path.dirname(__file__),"subprog.py")])

runit()

os.system("touch helloworld.c")
os.system("python3 setup.py build")
os.system("python3 setup.py install --user")

runit()

使用sys.executable确保相同蟒可执行用于主蟒过程和子过程,所以这是更透明的。

© www.soinside.com 2019 - 2024. All rights reserved.