2012-04-05 00:28:48 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
"""
|
|
|
|
configfile.py - Human-readable text configuration file library
|
|
|
|
Copyright 2010 Luke Campagnola
|
2019-08-17 03:16:01 +00:00
|
|
|
Distributed under MIT/X11 license. See license.txt for more information.
|
2012-04-05 00:28:48 +00:00
|
|
|
|
|
|
|
Used for reading and writing dictionary objects to a python-like configuration
|
|
|
|
file format. Data structures may be nested and contain any data type as long
|
|
|
|
as it can be converted to/from a string using repr and eval.
|
|
|
|
"""
|
|
|
|
|
2017-11-01 23:57:45 +00:00
|
|
|
import re, os, sys, datetime
|
2015-05-19 13:29:55 +00:00
|
|
|
import numpy
|
2013-02-25 04:09:03 +00:00
|
|
|
from .pgcollections import OrderedDict
|
2012-05-11 22:05:41 +00:00
|
|
|
from . import units
|
2015-05-19 13:29:55 +00:00
|
|
|
from .python2_3 import asUnicode, basestring
|
2014-08-07 13:03:26 +00:00
|
|
|
from .Qt import QtCore
|
|
|
|
from .Point import Point
|
|
|
|
from .colormap import ColorMap
|
2015-05-19 13:29:55 +00:00
|
|
|
GLOBAL_PATH = None # so not thread safe.
|
|
|
|
|
2012-04-05 00:28:48 +00:00
|
|
|
|
|
|
|
class ParseError(Exception):
|
|
|
|
def __init__(self, message, lineNum, line, fileName=None):
|
|
|
|
self.lineNum = lineNum
|
|
|
|
self.line = line
|
2020-07-06 05:52:15 +00:00
|
|
|
self.message = message
|
2012-04-05 00:28:48 +00:00
|
|
|
self.fileName = fileName
|
|
|
|
Exception.__init__(self, message)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
if self.fileName is None:
|
|
|
|
msg = "Error parsing string at line %d:\n" % self.lineNum
|
|
|
|
else:
|
|
|
|
msg = "Error parsing config file '%s' at line %d:\n" % (self.fileName, self.lineNum)
|
2019-06-23 05:17:14 +00:00
|
|
|
msg += "%s\n%s" % (self.line, Exception.__str__(self))
|
2012-04-05 00:28:48 +00:00
|
|
|
return msg
|
|
|
|
|
|
|
|
|
|
|
|
def writeConfigFile(data, fname):
|
|
|
|
s = genString(data)
|
2019-11-12 16:45:42 +00:00
|
|
|
with open(fname, 'w') as fd:
|
|
|
|
fd.write(s)
|
|
|
|
|
|
|
|
|
2012-04-05 00:28:48 +00:00
|
|
|
def readConfigFile(fname):
|
|
|
|
#cwd = os.getcwd()
|
|
|
|
global GLOBAL_PATH
|
|
|
|
if GLOBAL_PATH is not None:
|
|
|
|
fname2 = os.path.join(GLOBAL_PATH, fname)
|
|
|
|
if os.path.exists(fname2):
|
|
|
|
fname = fname2
|
2014-08-07 13:03:26 +00:00
|
|
|
|
2012-04-05 00:28:48 +00:00
|
|
|
GLOBAL_PATH = os.path.dirname(os.path.abspath(fname))
|
|
|
|
|
|
|
|
try:
|
|
|
|
#os.chdir(newDir) ## bad.
|
2019-11-12 16:45:42 +00:00
|
|
|
with open(fname) as fd:
|
|
|
|
s = asUnicode(fd.read())
|
2012-04-05 00:28:48 +00:00
|
|
|
s = s.replace("\r\n", "\n")
|
|
|
|
s = s.replace("\r", "\n")
|
|
|
|
data = parseString(s)[1]
|
|
|
|
except ParseError:
|
|
|
|
sys.exc_info()[1].fileName = fname
|
|
|
|
raise
|
|
|
|
except:
|
2012-05-11 22:05:41 +00:00
|
|
|
print("Error while reading config file %s:"% fname)
|
2012-04-05 00:28:48 +00:00
|
|
|
raise
|
|
|
|
#finally:
|
|
|
|
#os.chdir(cwd)
|
|
|
|
return data
|
|
|
|
|
|
|
|
def appendConfigFile(data, fname):
|
|
|
|
s = genString(data)
|
2019-11-12 16:45:42 +00:00
|
|
|
with open(fname, 'a') as fd:
|
|
|
|
fd.write(s)
|
2012-04-05 00:28:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
def genString(data, indent=''):
|
|
|
|
s = ''
|
|
|
|
for k in data:
|
|
|
|
sk = str(k)
|
|
|
|
if len(sk) == 0:
|
2012-05-11 22:05:41 +00:00
|
|
|
print(data)
|
2012-04-05 00:28:48 +00:00
|
|
|
raise Exception('blank dict keys not allowed (see data above)')
|
|
|
|
if sk[0] == ' ' or ':' in sk:
|
2012-05-11 22:05:41 +00:00
|
|
|
print(data)
|
2012-04-05 00:28:48 +00:00
|
|
|
raise Exception('dict keys must not contain ":" or start with spaces [offending key is "%s"]' % sk)
|
|
|
|
if isinstance(data[k], dict):
|
|
|
|
s += indent + sk + ':\n'
|
|
|
|
s += genString(data[k], indent + ' ')
|
|
|
|
else:
|
2019-06-23 05:17:14 +00:00
|
|
|
s += indent + sk + ': ' + repr(data[k]).replace("\n", "\\\n") + '\n'
|
2012-04-05 00:28:48 +00:00
|
|
|
return s
|
|
|
|
|
|
|
|
def parseString(lines, start=0):
|
|
|
|
|
|
|
|
data = OrderedDict()
|
|
|
|
if isinstance(lines, basestring):
|
2019-06-23 05:17:14 +00:00
|
|
|
lines = lines.replace("\\\n", "")
|
2012-04-05 00:28:48 +00:00
|
|
|
lines = lines.split('\n')
|
2012-05-11 22:05:41 +00:00
|
|
|
lines = [l for l in lines if re.search(r'\S', l) and not re.match(r'\s*#', l)] ## remove empty lines
|
2012-04-05 00:28:48 +00:00
|
|
|
|
|
|
|
indent = measureIndent(lines[start])
|
|
|
|
ln = start - 1
|
|
|
|
|
|
|
|
try:
|
|
|
|
while True:
|
|
|
|
ln += 1
|
|
|
|
#print ln
|
|
|
|
if ln >= len(lines):
|
|
|
|
break
|
|
|
|
|
|
|
|
l = lines[ln]
|
|
|
|
|
|
|
|
## Skip blank lines or lines starting with #
|
|
|
|
if re.match(r'\s*#', l) or not re.search(r'\S', l):
|
|
|
|
continue
|
|
|
|
|
|
|
|
## Measure line indentation, make sure it is correct for this level
|
|
|
|
lineInd = measureIndent(l)
|
|
|
|
if lineInd < indent:
|
|
|
|
ln -= 1
|
|
|
|
break
|
|
|
|
if lineInd > indent:
|
|
|
|
#print lineInd, indent
|
|
|
|
raise ParseError('Indentation is incorrect. Expected %d, got %d' % (indent, lineInd), ln+1, l)
|
|
|
|
|
|
|
|
|
|
|
|
if ':' not in l:
|
|
|
|
raise ParseError('Missing colon', ln+1, l)
|
|
|
|
|
|
|
|
(k, p, v) = l.partition(':')
|
|
|
|
k = k.strip()
|
|
|
|
v = v.strip()
|
|
|
|
|
|
|
|
## set up local variables to use for eval
|
|
|
|
local = units.allUnits.copy()
|
|
|
|
local['OrderedDict'] = OrderedDict
|
|
|
|
local['readConfigFile'] = readConfigFile
|
2014-08-07 13:03:26 +00:00
|
|
|
local['Point'] = Point
|
|
|
|
local['QtCore'] = QtCore
|
|
|
|
local['ColorMap'] = ColorMap
|
2017-11-01 23:57:45 +00:00
|
|
|
local['datetime'] = datetime
|
2014-08-07 13:03:26 +00:00
|
|
|
# Needed for reconstructing numpy arrays
|
|
|
|
local['array'] = numpy.array
|
|
|
|
for dtype in ['int8', 'uint8',
|
|
|
|
'int16', 'uint16', 'float16',
|
|
|
|
'int32', 'uint32', 'float32',
|
|
|
|
'int64', 'uint64', 'float64']:
|
|
|
|
local[dtype] = getattr(numpy, dtype)
|
|
|
|
|
2012-04-05 00:28:48 +00:00
|
|
|
if len(k) < 1:
|
|
|
|
raise ParseError('Missing name preceding colon', ln+1, l)
|
|
|
|
if k[0] == '(' and k[-1] == ')': ## If the key looks like a tuple, try evaluating it.
|
|
|
|
try:
|
|
|
|
k1 = eval(k, local)
|
|
|
|
if type(k1) is tuple:
|
|
|
|
k = k1
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
if re.search(r'\S', v) and v[0] != '#': ## eval the value
|
|
|
|
try:
|
|
|
|
val = eval(v, local)
|
|
|
|
except:
|
|
|
|
ex = sys.exc_info()[1]
|
|
|
|
raise ParseError("Error evaluating expression '%s': [%s: %s]" % (v, ex.__class__.__name__, str(ex)), (ln+1), l)
|
|
|
|
else:
|
|
|
|
if ln+1 >= len(lines) or measureIndent(lines[ln+1]) <= indent:
|
|
|
|
#print "blank dict"
|
|
|
|
val = {}
|
|
|
|
else:
|
|
|
|
#print "Going deeper..", ln+1
|
|
|
|
(ln, val) = parseString(lines, start=ln+1)
|
|
|
|
data[k] = val
|
|
|
|
#print k, repr(val)
|
|
|
|
except ParseError:
|
|
|
|
raise
|
|
|
|
except:
|
|
|
|
ex = sys.exc_info()[1]
|
|
|
|
raise ParseError("%s: %s" % (ex.__class__.__name__, str(ex)), ln+1, l)
|
|
|
|
#print "Returning shallower..", ln+1
|
|
|
|
return (ln, data)
|
|
|
|
|
|
|
|
def measureIndent(s):
|
|
|
|
n = 0
|
|
|
|
while n < len(s) and s[n] == ' ':
|
|
|
|
n += 1
|
|
|
|
return n
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
import tempfile
|
|
|
|
cf = """
|
|
|
|
key: 'value'
|
2012-04-05 02:54:46 +00:00
|
|
|
key2: ##comment
|
|
|
|
##comment
|
|
|
|
key21: 'value' ## comment
|
|
|
|
##comment
|
2012-04-05 00:28:48 +00:00
|
|
|
key22: [1,2,3]
|
|
|
|
key23: 234 #comment
|
|
|
|
"""
|
2019-11-12 16:45:42 +00:00
|
|
|
fn = tempfile.mktemp()
|
|
|
|
with open(fn, 'w') as tf:
|
|
|
|
tf.write(cf)
|
2012-05-11 22:05:41 +00:00
|
|
|
print("=== Test:===")
|
2012-04-05 02:54:46 +00:00
|
|
|
num = 1
|
|
|
|
for line in cf.split('\n'):
|
2012-05-11 22:05:41 +00:00
|
|
|
print("%02d %s" % (num, line))
|
2012-04-05 02:54:46 +00:00
|
|
|
num += 1
|
2012-05-11 22:05:41 +00:00
|
|
|
print(cf)
|
|
|
|
print("============")
|
2012-04-05 00:28:48 +00:00
|
|
|
data = readConfigFile(fn)
|
2012-05-11 22:05:41 +00:00
|
|
|
print(data)
|
2013-02-25 04:09:03 +00:00
|
|
|
os.remove(fn)
|