在执行之间保存和恢复变量的值 [英] Saving and recovering values of variables between executions

查看:59
本文介绍了在执行之间保存和恢复变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Python 模块,它用作无线手持计算机的服务器.手持设备每次向服务器发送消息时,模块都会确定它是哪种消息,然后组合出适当的响应.由于响应通常取决于状态,因此我在需要在处理每种类型消息的各个函数之间保留/共享信息时使用全局变量.

我遇到的问题是当应用程序关闭时(无论出于何种原因),全局变量值(当然)会丢失,因此在重新启动应用程序时它与手持设备不同步.我需要一种可靠的方法来存储这些值以进行恢复.

我到目前为止(但还没有让它工作)的方向是每次更新时将变量名称和它们的值写入磁盘上的 CSV 文件——然后(当应用程序启动),查找该文件并使用它来将变量分配给它们之前的状态.我在写入或读取文件时没有遇到任何问题,但由于某种原因,这些值没有得到分配.

我可以发布代码以供评论/帮助,但在此之前我想知道我是否一开始就走错了方向.有没有更好(或至少更可取)的方法来保存和恢复这些值?

谢谢,JDM

====

跟进.这可能有点笨拙,但这是我所拥有的并且正在运行.我唯一关心的是那些以CUR_"开头的全局变量.我不得不使用 tempDict1 因为解释器似乎不喜欢直接迭代 globals().

<前>进口泡菜CUR_GLO1 = 'valglo1'CUR_GLO2 = 'valglo2'CUR_GLO3 = 'valglo3'def saveGlobs():tempDict1 = globals().copy()tempDict2 = {}对于 tempDict1 中的键:if (key[:4]=='CUR_'):tempDict2[key] = tempDict1[key]pickle.dump(tempDict2,open('tempDict.p','wb'))defretrieveGlobs():tempDict = pickle.load(open('tempDict.p','rb'))全局().更新(tempDict)

解决方案

写下来作为答案..

我认为您想要做的是一种应用程序检查点.

您可以使用 Pickle 模块来方便地保存和加载 Python 变量.这是一个关于如何使用它的简单示例.关于 Stackoverflow 的讨论this note 似乎同意,尽管我的一部分认为必须有一个更好的方法.

顺便说一句,您不需要将所有内容都放入字典中.只要您以正确的顺序转储和加载变量,并确保不更改它,在中间插入数据等,您就可以转储和加载多个变量.像您一样使用字典确实可以消除排序依赖.

% 蟒蛇Python 2.6.1(r261:67515,2010 年 6 月 24 日,21:47:49)[GCC 4.2.1 (Apple Inc. build 5646)] 在达尔文上输入帮助"、版权"、信用"或许可"以获取更多信息.>>>进口泡菜>>>富=123>>>酒吧=你好">>>d={'abc': 123, 'def': 456}>>>f=open('p.pickle', 'wb')>>>pickle.dump(foo, f)>>>泡菜.转储(酒吧,F)>>>泡菜.转储(d,f)>>>^D% PythonPython 2.6.1(r261:67515,2010 年 6 月 24 日,21:47:49)[GCC 4.2.1 (Apple Inc. build 5646)] 在达尔文上输入帮助"、版权"、信用"或许可"以获取更多信息.>>>进口泡菜>>>f=open('p.pickle','rb')>>>foo=pickle.load(f)>>>富123>>>bar=pickle.load(f)>>>酒吧'你好'>>>d=pickle.load(f)>>>d{'abc':123,'def':456}>>>

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 kind of message it is, and then assembles an appropriate response. Because the responses are often state-dependent, I am using global variables where needed to retain/share information between the individual functions that handle each type of message.

The problem I'm having is when the application is closed (for whatever reason), the global variable values are (of course) lost, so on re-launching the application it's out of synch with the handheld. I need a reliable way to store those values for recovery.

The direction I've gone so far (but have not gotten it to work yet) is to write the variable names and their values to a CSV file on the disk, every time they're updated -- and then (when the app is launched), look for that file and use it to assign the variables to their previous states. I have no trouble writing the file or reading it, but for some reason the values just aren't getting assigned.

I can post the code for comments/help, but before that I wanted to find out whether I'm just going an entirely wrong direction in the first place. Is there a better (or at least preferable) way to save and recover these values?

thanks, JDM

====

Following up. It may be a touch klunky, but here's what I have and it's working. The only globals I care about are the ones that start with "CUR_". I had to use tempDict1 because the interpreter doesn't seem to like iterating directly over globals().

    import pickle
    CUR_GLO1 = 'valglo1'
    CUR_GLO2 = 'valglo2'
    CUR_GLO3 = 'valglo3'

    def saveGlobs():
        tempDict1 = globals().copy()
        tempDict2 = {}
        for key in tempDict1:
            if (key[:4]=='CUR_'):tempDict2[key] = tempDict1[key]
        pickle.dump(tempDict2,open('tempDict.p','wb'))

    def retrieveGlobs():
        tempDict = pickle.load(open('tempDict.p','rb'))
        globals().update(tempDict)

解决方案

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}
>>> 

这篇关于在执行之间保存和恢复变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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