Package rats :: Module statesaving
[hide private]
[frames] | no frames]

Source Code for Module rats.statesaving

 1  #!/usr/bin/env python 
 2  """ 
 3  State saving tools 
 4   
 5  Two json modules exist. We must use the simplejson that became  
 6  the standard json module in Python 2.6 
 7  """ 
 8  try: 
 9      import json # python 2.6 
10  except ImportError: 
11      import simplejson as json # python 2.4 to 2.5 
12  try: 
13      _tmp = json.loads 
14  except AttributeError: 
15      import warnings 
16      import sys 
17      warnings.warn("Use simplejson, not the old json module.") 
18      sys.modules.pop('json') # get rid of the bad json module 
19      import simplejson as json 
20   
21 -class StateSavingError(Exception):
22 """ 23 Any error the Saver class can generate. 24 """ 25 pass
26
27 -def save(file_name, data):
28 """ 29 State saving using JSON 30 31 The data attribute is a dict of basic types. 32 (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) 33 It can contain dicts and lists as well. 34 """ 35 try: 36 f = open(file_name, "w") 37 except IOError, e: 38 raise StateSavingError(e.message) 39 json.dump(data, f, indent=4) 40 f.close()
41
42 -def load(file_name):
43 try: 44 f = open(file_name, "r") 45 except IOError, e: 46 raise StateSavingError(e.message) 47 data = json.load(f) 48 f.close() 49 return data
50 51 if __name__ == "__main__": 52 import tempfile 53 filename = tempfile.mktemp() 54 print("Loading from %s" % (filename)) 55 try: 56 data = load(file_name) 57 except StateSavingError, e: 58 print(e.message) 59 pass 60 print("data: %s" %(data)) 61 data['x'] = 2 62 data['y'] = 3.14159 63 data['z'] = [1,2,3,4,5,6] 64 data['a'] = {'egg':'white', 'ham':'pink'} 65 print("data: %s" %(data)) 66 print("Saving to %s" % (file_name)) 67 save(file_name, data) 68