有没有办法在python中保存变量值如果树莓派电源出现故障?

问题描述 投票:1回答:2

有没有办法在python中保存变量值如果出现电源故障,那么当我再次运行程序时,它不会从初始值开始,而是从最后保存的值开始。在下面的代码中我计算的次数是按下按钮,我可以保存年龄值,并从15开始的保存值开始计数。

 import RPi.GPIO as GPIO
 import time
 age=15                   //initialize for debugging
 GPIO.setmode(GPIO.BCM)
 GPIO.setup(25, GPIO.IN,GPIO.PUD_DOWN)

 def led(channel):                     //funtion for increnment age
     global age
     age=(age+1)
     print(age)

PIN 7 AND 3.3V

normally 0 when connected 1

 GPIO.add_event_detect(25, GPIO.RISING, callback=led, bouncetime=1000 )
 print(age)
 try:
     while(True):
            time.sleep(1)
 except KeyboardInterrupt:
           GPIO.cleanup()
           print (age)
           print ("Exiting")
python raspberry-pi
2个回答
0
投票

试试这个:

打开终端并键入以下内容以创建名为“led.txt”的文件:

>>>import pickle    
>>>s={'age':None}    
>>>with open('led.txt','w') as f:
...        f.write(pickle.dumps(s))

然后继续你的代码

 import RPi.GPIO as GPIO
 import time
 import pickle

 led_age={'age':None}  # initialise as dictionary

 with open('led.txt') as f: # open file in read mode  
   led_age = pickle.loads(f.read())  #initialize for debugging

 GPIO.setmode(GPIO.BCM)
 GPIO.setup(25, GPIO.IN,GPIO.PUD_DOWN)


 def led(channel): 
     global led_age       

     led_age['age'] += 1     # increment value
     with open('led.txt','w') as f:    # again open the file in write mode
       f.write(pickle.dumps(led_age))  #pickle the dictionary and write back to the file

     print(led_age)

而不是int变量我使用了字典。

函数led执行以下操作:

  1. 以只读模式(默认模式)打开文件'led.txt'并加载字典
  2. 增加'年龄'
  3. 再次打开文件'led.txt'但在写模式下并写回更新的字典

pickle.dumps将字典序列化为字符串,pickle.loads进行反序列化

每次调用函数led时,都会自动执行此更新,并更新led.txt文件。

注意:pickle的替代方法可以是JSON,它与其他语言兼容


0
投票

执行此操作的典型方法是通过写入和写入文件。您可以在启动程序时从文件中读取程序状态,并在变量状态更改时修改文件。

为了保存更复杂的数据结构,存在Pickle模块。这允许对象序列化。

© www.soinside.com 2019 - 2024. All rights reserved.