comparison py/params.py @ 233:19569cb5ed46

better arg parser. seems close to ready
author Matt Johnston <matt@ucc.asn.au>
date Sat, 11 Apr 2015 23:32:59 +0800
parents e39ed85d87a5
children 0a1b642e3086
comparison
equal deleted inserted replaced
232:a01b7bccccd3 233:19569cb5ed46
31 def __setattr__(self, k, v): 31 def __setattr__(self, k, v):
32 # fail if we set a bad value 32 # fail if we set a bad value
33 self[k] 33 self[k]
34 self[k] = v 34 self[k] = v
35 35
36 def load(self, f = None): 36 def _do_load(self, f):
37 if not f:
38 try:
39 f = open(config.PARAMS_FILE, 'r')
40 except IOError as e:
41 W("Missing parameter file, using defaults. %s", e)
42 return
43 try: 37 try:
44 u = json.load(f) 38 u = json.load(f)
45 except Exception as e: 39 except Exception as e:
46 raise self.Error(e) 40 raise self.Error(e)
47 41
53 self.update(u) 47 self.update(u)
54 48
55 L("Loaded parameters") 49 L("Loaded parameters")
56 L(self.save_string()) 50 L(self.save_string())
57 51
52 def load(self, f = None):
53 if f:
54 return self._do_load(f)
55 else:
56 with open(config.PARAMS_FILE, 'r') as f:
57 try:
58 return self._do_load(f)
59 except IOError as e:
60 W("Missing parameter file, using defaults. %s" % str(e))
61 return
58 62
59 def save(self, f = None): 63 def _do_save(self, f):
60 if not f:
61 f = file(config.PARAMS_FILE, 'w')
62 json.dump(self, f, sort_keys=True, indent=4) 64 json.dump(self, f, sort_keys=True, indent=4)
63 f.write('\n') 65 f.write('\n')
64 f.flush() 66 f.flush()
67
68 def save(self, f = None):
69 if f:
70 return self._do_save(f)
71 else:
72 with file(config.PARAMS_FILE, 'w') as f:
73 return self._do_save(f)
65 74
66 def save_string(self): 75 def save_string(self):
67 s = io.StringIO() 76 s = io.StringIO()
68 self.save(s) 77 self.save(s)
69 return s.getvalue() 78 return s.getvalue()