- 论坛徽章:
- 0
|
也来凑个热闹
支持默认值和多行属性
- '''
- The <code>Properties</code> class represents a persistent set of
- properties. The <code>Properties</code> can be saved to a stream
- or loaded from a stream. Each key and its corresponding value in
- the property list is a string.
- <p>
- A property list can contain another property list as its
- "defaults"; this second property list is searched if
- the property key is not found in the original property list.
- </p>
- '''
- class Properties:
- def __init__(self, prop={}, default={}):
- self.prop = prop
- self.default = default
- def put(self, key, value):
- self.prop[key] = value
- def get(self, key, default=None):
- return self.prop.get(key, self.default.get(key, default))
- def load(self, filename):
- import os
- if os.path.exists(filename) and os.path.isfile(filename):
- fd = open(filename, 'r')
- lines = fd.readlines()
- fd.close()
- keyvalue = ''
- continueLine = False
- for i in range(len(lines)):
- line = lines[i].strip()
- if line[0] == '#':
- continue
- if continueLine:
- if line[-1:] == '\\':
- line = line[:-1]
- keyvalue += line
- continue
- else:
- keyvalue += line
- continueLine = False
- else:
- if line[-1:] == '\\':
- keyvalue = line[:-1]
- continueLine = True
- continue
- else:
- keyvalue = line
- continueLine = False
- if keyvalue.find('=') < 0:
- continue
- key, value = keyvalue.split('=', 1)
- self.prop[key.strip()] = value.strip()
- if __name__ == '__main__':
- p = Properties({'propname':'propname'}, {'defaultname':'defaultname'})
- p.load('test.properties')
- print p.get('noname'), p.get('noname', 'default-name')
- print p.get('name'), p.get('name', 'default-name')
- print p.get('propname'), p.get('propname', 'default-name')
- print p.get('defaultname'), p.get('defaultname', 'default-name')
- print p.get('value'), p.get('value', 'default-value')
复制代码
用于测试的test.properties文件内容
- # Properties test
- name = properties name
- value = multi-\
- line \
- value \
- properties
- dirty lines
- # noname = end lines
复制代码
[ 本帖最后由 jkit 于 2005-11-29 14:35 编辑 ] |
|