在IPython中保存工作区

qkh*_*hly 17 python ipython

是否可以保存IPython工作区(定义的函数,不同类型的变量等),以便以后加载它?

这与save.image()MATLAB或R中的功能类似.之前已经提出了类似的问题,例如:

像在MATLAB中一样在IPython中保存会话?

但是,几年过去了,我想知道现在是否有一个好的解决方案.

toe*_*oes 8

编辑:此答案(和要点)已被修改为适用于IPython 6

我添加了一个有点特别的解决方案,它使用IPython的%store magic中的底层代码自动化存储/恢复用户空间变量的过程,这是我理解你想要的.在这里看到要点.请注意,这仅适用于可以腌制的对象.

我不能保证它的健壮性,特别是如果IPython中的任何autorestore机制在未来发生变化,但它一直在为IPython 2.1.0工作.希望这至少会指向正确的方向.

重申这里的解决方案:

  1. 将下面的save_user_variables.py脚本添加到您的ipython文件夹(默认情况下为$ HOME/.ipython).此脚本负责在退出时保存用户变量.
  2. 将此行添加到您的配置文件的ipython启动脚本(例如,$ HOME/.ipython/profile_default/startup/startup.py):

    get_ipython().ex("import save_user_variables;del save_user_variables")

  3. 在您的ipython配置文件配置文件中(默认为$ HOME/.ipython/profile_default/ipython_config.py),找到以下行:

    # c.StoreMagics.autorestore = False

    取消注释并将其设置为true.这会在启动时自动重新加载存储的变量.或者,您可以使用%store -r手动重新加载上一个会话.

save_user_variables.py

def get_response(quest,default=None,opts=('y','n'),please=None,fmt=None):
    try:
        raw_input = input
    except NameError:
        pass
    quest += " ("
    quest += "/".join(['['+o+']' if o==default else o for o in opts])
    quest += "): "

    if default is not None: opts = list(opts)+['']
    if please is None: please = quest
    if fmt is None: fmt = lambda x: x

    rin = input(quest)
    while fmt(rin) not in opts: rin = input(please)

    return default if default is not None and rin == '' else fmt(rin)

def get_user_vars():
    """
    Get variables in user namespace (ripped directly from ipython namespace
    magic code)
    """
    import IPython
    ip = IPython.get_ipython()    
    user_ns = ip.user_ns
    user_ns_hidden = ip.user_ns_hidden
    nonmatching = object()
    var_hist = [ i for i in user_ns
                 if not i.startswith('_') \
                 and (user_ns[i] is not user_ns_hidden.get(i, nonmatching)) ]
    return var_hist

def shutdown_logger():
    """
    Prompts for saving the current session during shutdown
    """
    import IPython, pickle
    var_hist = get_user_vars()
    ip = IPython.get_ipython()
    db = ip.db

    # collect any variables that need to be deleted from db
    keys = map(lambda x: x.split('/')[1], db.keys('autorestore/*'))
    todel = set(keys).difference(ip.user_ns)
    changed = [db[k] != ip.user_ns[k.split('/')[1]]
               for k in db.keys('autorestore/*') if k.split('/')[1] in ip.user_ns]

    try:
        if len(var_hist) == 0 and len(todel) == 0 and not any(changed): return
        if get_response("Save session?", 'n', fmt=str.lower) == 'n': return
    except KeyboardInterrupt:
        return

    # Save interactive variables (ignore unsaveable ones)
    for name in var_hist:
        obj = ip.user_ns[name]
        try:
            db[ 'autorestore/' + name ] = obj
        except pickle.PicklingError:
            print("Could not store variable '%s'. Skipping..." % name)
            del db[ 'autorestore/' + name ]

    # Remove any previously stored variables that were deleted in this session
    for k in todel:
        del db['autorestore/'+k]

import atexit
atexit.register(shutdown_logger)
del atexit
Run Code Online (Sandbox Code Playgroud)


Fra*_*urt 6

您可以使用dill python 包:

import dill                            
filepath = 'session.pkl'
dill.dump_session(filepath) # Save the session
dill.load_session(filepath) # Load the session
Run Code Online (Sandbox Code Playgroud)

要安装它:

pip install dill
Run Code Online (Sandbox Code Playgroud)


dou*_*oug -4

您当然可以在 ipython笔记本中执行此操作。

当笔记本保存时(手动或默认配置),笔记本将保存为.ipynb文件,该文件只是一个json文件(github gist 中的示例)。

下次您在该文件所在的目录中启动 ipython 服务器时,服务器将检测到它。

当您在浏览器中打开该笔记本时,所有代码和配置都在那里但未执行;您可以通过从单元格菜单中选择执行所有单元格来执行每个单元格中的代码。

此外,您可以手动保留笔记本的快照,如ipynb_checkpoints,它们存储在该名称前面带有点的目录中。

最后,从文件菜单选项中,您可以将笔记本保留为纯 python 源文件 ( .py )

  • @doug,(再次)执行代码可能非常不切实际,例如可能需要几个小时,所以它并不总是问题的可行解决方案。 (7认同)