如何使IPython重新加载传递给“IPython I…”的文件`

2024-05-20 03:14:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个/tmp/throwaway文件_代码.py有点像

def hello():
    print("world")

和IPython一起试试:

^{pr2}$

现在我更改了文件中的某些内容并想重新加载。如何在不重新启动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)?在


Tags: 文件代码inpy内容helloworldreturn
2条回答

在IPython3中,使用reload(mymodule),可以在同一个包中重新加载所有模块。把这个代码粘贴在重新加载.py在IPython3启动文件夹中(在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__)

autoreload在这里不起作用,模块不是用-i选项放在sys.modules中:

from sys import modules

modules['throwaway_code'] # KeyError

因此reload找不到您希望它重新加载的模块。在

一种解决方法是显式地import将它放在sys.modules中的模块,然后{}每次都会获取更改。所以您应该退出IPython并用适当的PYTHONPATH启动它,这样您的代码就可以作为模块导入。您的会话应该如下所示:

^{pr2}$

相关问题 更多 >