[英]How do I make IPython reload a file passed to `ipython -i …`
我有一个文件/tmp/throwaway_code.py
def hello():
print("world")
并尝试使用IPython:
$ ipython3 -i /tmp/throwaway_code.py
In [1]: hello()
world
现在我改变了文件中的内容并想重新加载。 如何在不重新启动IPython或模块化代码的情况下执行此操作?
我失败的尝试:
In [2]: %load_ext autoreload
In [3]: %autoreload 2
# change source file
In [4]: hello()
world
# Expected: world2.
或者,如何以最小的努力离开并重新进入IPython会话(目前有6次击键:Ctrl,D,y,Return,Up,Return)?
autoreload
在这里不起作用,模块没有放在带有-i
选项的sys.modules
:
from sys import modules
modules['throwaway_code'] # KeyError
所以reload
将找不到您想要重新加载的模块。
解决它的方法是显式import
将其放在sys.modules
的模块,然后autoreload
将每次都获取更改。 因此,您应该退出IPython并使用适当的PYTHONPATH
启动它,以便您的代码可以作为模块导入。 您的会话应如下所示:
In [4]: ^D
Do you really want to exit ([y]/n)? y
$ PYTHONPATH=/tmp ipython3
In [1]: from throwaway_code import *
In [2]: %load_ext autoreload
In [3]: %autoreload 2
In [4]: hello()
world
In [5]: hello()
world2
在IPython3中,使用reload(mymodule),您可以在同一个包中重新加载所有模块。 只需将此代码粘贴到IPython3启动文件夹中的reload.py(On Ubuntu是“〜/ .ipython / profile_default / startup /”)
import importlib
from types import ModuleType
import compileall
from filecmp import dircmp
from os.path import dirname
from glob import glob
from os.path import join
blacklist=[]
def reload(module,blacklist_appendix=[]):
"""Recursively reload modules."""
file_paths=glob(join(dirname(module.__file__),"*.py"))
print(file_paths)
_reload(module,blacklist+blacklist_appendix,file_paths)
def _reload(module, blacklist=[],file_paths=[],reloadeds=[]):
if module.__name__ in blacklist:
print("not reloaded: "+module.__name__)
return False
if (module.__dict__.get("__file__")==None
or not (module.__file__ in file_paths)
or module.__file__ in reloadeds):
return False
reloadeds.append(module.__file__ )
for attribute_name in dir(module):
attribute = getattr(module, attribute_name)
if type(attribute) is ModuleType:
_reload(attribute,file_paths=file_paths,reloadeds=reloadeds)
compileall.compile_file(module.__file__,force=True)
print("reload start: "+module.__name__)
importlib.reload(module)
print("reloaded: "+module.__name__)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.