python shell: pickle entire state

前端 未结 1 1731
攒了一身酷
攒了一身酷 2021-01-14 07:38

When using either \"ipython\" or \"code.interact(local=locals())\", I\'d like to have a way to save the entire program address space into a pickle

1条回答
  •  余生分开走
    2021-01-14 08:15

    To do this, I'd use dill, which can serialize almost anything in python.

    >>> import dill
    >>> 
    >>> def foo(a):
    ...   def bar(x):
    ...     return a*x
    ...   return bar
    ... 
    >>> class baz(object):
    ...   def __call__(self, a,x):
    ...     return foo(a)(x)
    ... 
    >>> b = baz()
    >>> b(3,2)
    6
    >>> c = baz.__call__
    >>> c(b,3,2)
    6
    >>> g = dill.loads(dill.dumps(globals()))
    >>> g
    {'dill': , 'c': , 'b': <__main__.baz object at 0x4d61970>, 'g': {...}, '__builtins__': , 'baz': , '_version': '2', '__package__': None, '__name__': '__main__', 'foo': , '__doc__': None}
    

    Dill registers it's types into the pickle registry, so if you have some black box code that uses pickle and you can't really edit it, then just importing dill can magically make it work without monkeypatching the 3rd party code.

    You also wanted to pickle the whole interpreter session... dill can do that too.

    >>> # continuing from above
    >>> dill.dump_session('foobar.pkl')
    >>>
    >>> ^D
    dude@sakurai>$ python
    Python 2.7.5 (default, Sep 30 2013, 20:15:49) 
    [GCC 4.2.1 (Apple Inc. build 5566)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import dill
    >>> dill.load_session('foobar.pkl')
    >>> c(b,3,2)
    6
    

    Dill also has some good tools for helping you understand what is causing your pickling to fail when your code fails.

    0 讨论(0)
提交回复
热议问题