configfile.py

changeset 132
a22c50f52a23
parent 124
7b2cd8b1ba86
child 146
c17b82b1f573
--- a/configfile.py	Fri Apr 24 06:40:08 2015 +0300
+++ b/configfile.py	Fri May 01 19:08:12 2015 +0300
@@ -26,7 +26,10 @@
 	THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 '''
 
-import json
+import json, sys
+IsInitialized = False
+Config = None
+ConfigFileName = ""
 
 class ConfigNode:
 	def __init__ (self, obj, name, parent):
@@ -45,7 +48,7 @@
 		
 		if not key in self.obj:
 			if default == None:
-				raise ValueError ('Mandatory key \'%s\' not found' % self.keyname (key))
+				raise ValueError ("""Mandatory key '%s' not found""" % self.keyname (key))
 			self.obj[key] = default
 			self.save()
 		
@@ -89,7 +92,7 @@
 			self.root.save()
 			return
 		
-		with open ('cobalt.json', 'w') as fp:
+		with open (ConfigFileName, 'w') as fp:
 			json.dump (self.obj, fp, sort_keys = True, indent = 1)
 		
 		print "Config saved."
@@ -102,16 +105,27 @@
 		return ''
 
 def init():
-	print 'Loading configuration...'
+	filename = 'cobalt.json'
+
+	if len (sys.argv) >= 2:
+		filename = sys.argv[1]
+
+	global IsInitialized
+	global ConfigFileName
+	ConfigFileName = filename
+
+	if not IsInitialized:
+		print """Loading configuration..."""
 
-	try:
-		with open ('cobalt.json', 'r') as fp:
-			jsondata = json.loads (fp.read())
-	except IOError as e:
-		print 'couldn\'t open cobalt.json: %s' % e
-		quit()
-	
-	global Config
-	Config = ConfigNode (jsondata, name=None, parent=None)
+		try:
+			with open (filename, 'r') as fp:
+				jsondata = json.loads (fp.read())
+		except IOError as e:
+			print ("""couldn't open %s: %s""" % (filename, e))
+			quit()
 
-init()
+		global Config
+		Config = ConfigNode (jsondata, name=None, parent=None)
+		IsInitialized = True
+
+init()
\ No newline at end of file

mercurial