gpt4 book ai didi

python - 如何强制 ipython 深度重新加载?

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:17 25 4
gpt4 key购买 nike

我正在通过 run magic 在 ipython 中运行一个脚本:

%run myscript.py

并且此脚本导入了我编写的各种模块,并且我经常在运行之间更改这些模块。我想自动重新加载这些模块,而不是必须重新启动 ipython。 stackoverflow 和其他地方有很多问题推荐

%load_ext autoreload
%autoreload 2

也许还有

 %aimport <your module>

投入使用以备不时之需。但这根本行不通。深度重载是否超出了 autoreload 的能力范围?是否有其他方法可以删除所有已加载的模块,或者以静默方式重新启动 ipython 所依赖的 python 后台进程?

编辑:在尝试了更多之后,自动重载失败似乎更加微妙。可能(我还不是 100% 确定)只有当我的模块的 __init__.py 正在做 from .<some file in the module> import * 时,autoreload 才会失败。 ,而不是按名称导入每个成员。我也试过 %reset神奇,但这似乎只是清空了命名空间,并没有清除缓存的模块。

顺便说一句,Spyder 能够强制重新加载模块,但我不确定这是如何完成的(某种围绕 ipython 的包装器会重新启动进程?)

最佳答案

我查阅了 Spyder 的解决方案,它基本上是在 sys.modules 上使用 del。下面我稍微修改了我在 ~/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py 中找到的代码,并将其放入名为 reloader.py 的模块:

import sys


def _is_module_deletable(modname, modpath):
if modname.startswith('_cython_inline'):
# Don't return cached inline compiled .PYX files
return False
for path in [sys.prefix]:
if modpath.startswith(path):
return False
else:
return set(modname.split('.'))


def clear():
"""
Del user modules to force Python to deeply reload them

Do not del modules which are considered as system modules, i.e.
modules installed in subdirectories of Python interpreter's binary
Do not del C modules
"""
log = []
for modname, module in list(sys.modules.items()):
modpath = getattr(module, '__file__', None)

if modpath is None:
# *module* is a C module that is statically linked into the
# interpreter. There is no way to know its path, so we
# choose to ignore it.
continue

if modname == 'reloader':
# skip this module
continue

modules_to_delete = _is_module_deletable(modname, modpath)
if modules_to_delete:
log.append(modname)
del sys.modules[modname]

print("Reloaded modules:\n\n%s" % ", ".join(log))

现在只需执行 import reloader 然后调用 reloader.clear()

关于python - 如何强制 ipython 深度重新加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49299033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com