在IPython中保存工作区 [英] Save workspace in IPython

查看:145
本文介绍了在IPython中保存工作区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to save an IPython workspace (defined functions, different kinds of variables, etc) so that it can be loaded later?

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

This would be a similar function to save.image() in MATLAB or R. Similar questions has been asked before, such as:

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

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

However, since a few years passed, I am wondering if there is a good solution now.

推荐答案


编辑:这个答案(以及 gist )已被修改为适用于IPython 6

this answer (and gist) has been modified to work for IPython 6

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

I added a somewhat ad-hoc solution that automates the process of storing/restoring user space variables using the underlying code from IPython's %store magic which is from what I understand what you wanted. See the gist here. Note that this only works for objects that can be pickled.

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

I can't guarantee its robustness, especially if any of the autorestore mechanisms in IPython change in the future, but it has been working for me with IPython 2.1.0. Hopefully this will at least point you in the right direction.


  1. 将下面的save_user_variables.py脚本添加到您的ipython文件夹(默认为$ HOME / .ipython)。此脚本负责在退出时保存用户变量。

  2. 将此行添加到配置文件的ipython启动脚本中(例如,$ HOME / .ipython / profile_default / startup / startup.py ):

  1. Add the save_user_variables.py script below to your ipython folder (by default $HOME/.ipython). This script takes care of saving user variables on exit.
  2. Add this line to your profile's ipython startup script (e.g., $HOME/.ipython/profile_default/startup/startup.py):

get_ipython()。ex(import save_user_variables; del save_user_variables)

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

In your ipython profile config file (by default $HOME/.ipython/profile_default/ipython_config.py) find the following line:

#c.StoreMagics.autorestore = False

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

Uncomment it and set it to true. This automatically reloads stored variables on startup. Alternatively you can reload the last session manually using %store -r.



save_user_variables.py



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

这篇关于在IPython中保存工作区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆