-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproperties.py
More file actions
80 lines (65 loc) · 2.41 KB
/
properties.py
File metadata and controls
80 lines (65 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/python
#-*- coding:utf-8 -*-
'''resolve properties file'''
import re
import os
import tempfile
def load_properties(file_name):
'''load a new Properoties instanse, you can chage the properties file'''
return Properties(file_name)
def load_properties_dict(file_name):
'''load a properties dict, you can not chage the properties file'''
return Properties(file_name).properties
class Properties(object):
'''properties reslover'''
def __init__(self, file_name):
self.file_name = file_name
self.properties = {}
try:
fopen = open(self.file_name, 'r')
for line in fopen:
line = line.strip()
if line.find('=') > 0 and not line.startswith('#'):
strs = line.split('=')
self.properties[strs[0].strip()] = strs[1].strip()
except Exception, ex:
raise ex
else:
fopen.close()
def has_key(self, key):
'''valid there has this key'''
return key in self.properties
def get(self, key, default_value=''):
'''get value of key'''
if key in self.properties:
return self.properties[key]
return default_value
def update(self, key, value):
'''update value of key'''
self.properties[key] = value
self.replace_properties(key + '=.*', key + '=' + value, True)
def replace_properties(self, old, new, append_on_not_exists=True):
'''replace properties file'''
tmpfile = tempfile.TemporaryFile()
if os.path.exists(self.file_name):
read_file = open(self.file_name, 'r')
pattern = re.compile(r'' + old)
found = None
for line in read_file:
if pattern.search(line) and not line.strip().startswith('#'):
found = True
line = re.sub(old, new, line)
tmpfile.write(line)
if not found and append_on_not_exists:
tmpfile.write('\n' + new)
read_file.close()
tmpfile.seek(0)
content = tmpfile.read()
if os.path.exists(self.file_name):
os.remove(self.file_name)
write_file = open(self.file_name, 'w')
write_file.write(content)
write_file.close()
tmpfile.close()
else:
print "file %s not found" % self.file_name