python - 修改后重新加载模块

标签 python python-import

是否有在编辑时重新加载 python 模块的惯用方法?我将配置保存在 my_config_module.py 文件中,并希望自动检测和加载配置更改。目前我正在尝试这样的事情,但我发现它丑陋且不安全:

import my_config_module
import importlib

last_modification = os.stat('my_config_module.py').st_mtime

while True:
    last_mod = os.stat('my_config_module.py').st_mtime
    if last_mod != last_modification:
        importlib.raload(my_config_module)
        last_modification = last_mod 
    # main loop, some of my code     

最佳答案

您应该将数据保存在单独的文件中,并在修改时重新加载它(从而避免重新加载代码的需要)。

关于python - 修改后重新加载模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58592116/

相关文章:

python - 编写适用于 CPython、Jython 和 IronPython 的 Python 代码有哪些策略?

python - pycharm不使用virtualenv python

python - 一次读取成对的图像文件

python - 在 Django 中从 View 导入模型

python - 带有 __init__.pyx : Possible? 的 Cython 包

python - '尝试在非包中进行相对导入'尽管包在一个目录中具有 __init__.py

从装饰器导入 Python 模块

python - 为什么 "import module"然后 "from package import module"再次加载模块?

python - 在python中解析字符串

python - 从 Pandas DataFrame 中选择与另一个 DataFrame 中的列值完全相同的行