Saving and recovering values of variables between executions

后端 未结 1 404
抹茶落季
抹茶落季 2020-12-18 15:31

I have a Python module that is operating as a server for a wireless handheld computer. Every time the handheld sends a message to the server, the module determines what kin

相关标签:
1条回答
  • 2020-12-18 16:04

    writing it up as an answer..

    What I think you want to do is a form of application checkpointing.

    You can use the Pickle module for conveniently saving and loading Python variables. Here is a simple example of how to use it. This discussion on Stackoverflow and this note seem to agree, although part of me thinks that there must be a better way.

    Incidentally, you don't need to put everything into a dictionary. As long as you dump and load variables in the right order, and make sure that you don't change that, insert data in the middle etc, you can just dump and load several variables. Using a dictionary like you did does remove the ordering dependency though.

    % python
    Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) 
    [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import pickle
    >>> foo=123
    >>> bar="hello"
    >>> d={'abc': 123, 'def': 456}
    >>> f=open('p.pickle', 'wb')
    >>> pickle.dump(foo, f)
    >>> pickle.dump(bar, f)
    >>> pickle.dump(d, f)
    >>> ^D
    % python
    Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) 
    [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import pickle
    >>> f=open('p.pickle','rb')
    >>> foo=pickle.load(f)
    >>> foo
    123
    >>> bar=pickle.load(f)
    >>> bar
    'hello'
    >>> d=pickle.load(f)
    >>> d
    {'abc': 123, 'def': 456}
    >>> 
    
    0 讨论(0)
提交回复
热议问题