forked from meetbill/MyPythonLib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_util.py
More file actions
157 lines (135 loc) · 5.19 KB
/
file_util.py
File metadata and controls
157 lines (135 loc) · 5.19 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#-*- coding: utf-8 -*-
"""Package for operations.
"""
import os
if __name__ == '__main__':
import sys
root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, root_path)
import re
import shlex
import subprocess
import sys
import linecache
reload(sys)
sys.setdefaultencoding('utf8')
# 需要修改,配置文件位置
CONFIG_CFG = '/etc/config'
#{{{loadconfig
def loadconfig(cfgfile=None, detail=False):
"""Read config file and parse config item to dict.
"""
if not cfgfile: cfgfile = CONFIG_CFG
settings = {}
with open(cfgfile) as f:
for line_i, line in enumerate(f):
# line_i[行号],line[每行内容]
# 删除空白符(包括'\n', '\r', '\t', ' ')
line = line.strip()
# 跳过空行和注释('# '开头的)
if not line or line.startswith('# '): continue
# detect if it's commented
if line.startswith('#'):
line = line.strip('#')
commented = True
if not detail: continue
else:
commented = False
# 将行以第一个'='分割
#########################################
fs = re.split('=', line, 1)
if len(fs) != 2: continue
item = fs[0].strip()
value = fs[1].strip()
if settings.has_key(item):
if detail: count = settings[item]['count']+1
if not commented:
settings[item] = detail and {
'file': cfgfile,
'line': line_i,
'value': value,
'commented': commented,
} or value
else:
count = 1
settings[item] = detail and {
'file': cfgfile,
'line': line_i,
'value': fs[1].strip(),
'commented': commented,
} or value
if detail: settings[item]['count'] = count
return settings
#}}}
#{{{cfg_get
def cfg_get(item, detail=False, config=None):
"""Get value of a config item.
"""
if not config: config = loadconfig(detail=detail)
if config.has_key(item):
return config[item]
else:
return None
#}}}
#{{{cfg_set
def cfg_set(item, value, commented=False, config=None):
"""Set value of a config item.
如果可以获取到key,则对key后的item进行修改
如果获取不到key,则直接在配置文件后进行追加一行
"""
cfgfile = CONFIG_CFG
v = cfg_get(item, detail=True, config=config)
#print v
if v:
# detect if value change
if v['commented'] == commented and v['value'] == value: return True
# empty value should be commented
# 如果有key,但是传的value值为空,会将此行进行注释
if value == '': commented = True
# replace item in line
lines = []
with open(v['file']) as f:
for line_i, line in enumerate(f):
if line_i == v['line']:
# 对没注释的行进行操作
if not v['commented']:
# 检测是否需要注释
if commented:
if v['count'] > 1:
# delete this line, just ignore it
pass
else:
# comment this line
#########################################
lines.append('#%s=%s\n' % (item, value))
else:
#########################################
lines.append('%s=%s\n' % (item, value))
else:
if commented:
# do not allow change comment value
lines.append(line)
pass
else:
# append a new line after comment line
lines.append(line)
#########################################
lines.append('%s=%s\n' % (item, value))
else:
lines.append(line)
with open(v['file'], 'w') as f: f.write(''.join(lines))
else:
# append to the end of file
with open(inifile, 'a') as f:
f.write('\n%s%s = %s\n' % (commented and '#' or '', item, value))
return True
#}}}
if __name__ == '__main__':
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(loadconfig())
#print cfg_get('xxxxxx')
#print cfg_get('Subsystem', detail=True)
#print cfg_set('xxxxxx', '44444333', commented=False)
#print cfg_set('Subsystem', 'sftp\t/usr/libexec/openssh/sftp-server', commented=True)
#print chlicense('aaaaaa')