涓嬮潰鏄垜鐨勫疄鐜頒唬鐮侊細
1 #coding=utf-8
2
3 '''
4 Created on 2010-7-12
5
6 @author: Innate Solitary
7
8 ini鏂囦歡瑙f瀽綾?br />
9 '''
10
11 import ConfigParser
12
13
14 class ConfigFile(object):
15 '''
16 閰嶇疆鏂囦歡瑙f瀽錛屽鐞嗙殑綆鍗曞疄鐜扮被
17 '''
18
19
20 def __init__(self, file_name):
21 '''
22 Constructor
23 '''
24 self.file_name = file_name
25 self.file = file(file_name)
26 self.cfg = ConfigParser.ConfigParser()
27 self.read_handle = None
28 self.write_handle = None
29 self.sections = []
30 self.items = {}
31 self.init_flag = False
32
33 def initialization(self):
34 '''
35 鍒濆鍖栭厤緗枃浠?br />
36 '''
37 try:
38 self.read_handle = open(self.file_name, 'r')
39 self.write_handle = open(self.file_name, 'w')
40 self.cfg.readfp(self.read_handle)
41 self.sections = self.cfg.sections()
42 for section in self.sections:
43 self.items[section] = self.cfg.items(section)
44 self.init_flag = True
45 except Exception, e:
46 print '鍒濆鍖栭厤緗枃浠墮敊璇?', str(e)
47 self.init_flag = False
48 return self.init_flag
49
50 def close(self):
51 '''
52 鍏抽棴閰嶇疆鏂囦歡
53 '''
54 self.read_handle.close()
55 del self.file
56 del self.read_handle
57 del self.file_name
58 del self.cfg
59 del self.sections
60 del self.items
61
62 def get_value(self, section, key, default = ''):
63 '''
64 寰楀埌鎸囧畾section涓嬬殑key鐨勫鹼紝濡傛灉娌掓湁緄﹀叾涓鍊嬬┖瀛楃涓插仛涓洪粯璁ゅ鹼紝騫跺姞鍏ユ枃浠朵腑
65 '''
66 if not self.init_flag:
67 raise Exception('鏈垵濮嬪寲閰嶇疆鏂囦歡錛岃鍦ㄥ鐞嗘枃浠跺墠璋冪敤initialization(self)榪涜閰嶇疆鏂囦歡鍒濆鍖?/span>')
68
69
70 if not self.cfg.has_section(section):
71 self.cfg.add_section(section)
72 if not self.cfg.has_option(section, key):
73 self.cfg.set(section, key, default)
74
75 value = self.cfg.get(section, key)
76
77
78 return value
79
80 def set_value(self, section, key, value):
81 '''
82 璁劇疆鍊?br />
83 '''
84
85 if not self.cfg.has_section(section):
86 self.cfg.add_section(section);
87
88 self.cfg.set(section, key, value)
89
90 def write_to_file(self, file = None):
91 if file != None and file.mode == 'r':
92 raise Exception('鏂囦歡妯″紡涓嶅彲鍐?/span>')
93 if file == None:
94 self.cfg.write(self.write_handle)
95 else:
96 self.cfg.write(file)
97
98
99
100
101
鎴戝湪榪欓噷浣跨敤浜咰onfigParser妯″潡錛岃繖閲屾垜鐨勮繖孌典唬鐮佸洜涓哄伐浣滅殑鍘熷洜鍙疄鐜頒簡涓閮ㄥ垎錛屽茍娌掓湁鎶婃垜褰撳垵鎯沖埌鐨勫姛鑳藉疄鐜幫紝浣嗘槸涔犻9錛?瑕佹眰鐨勫姛鑳介兘瀹炵幇浜嗭紝浠g爜寰堢畝鍗曚釜浜鴻娌掓湁浠涔堥毦寰楁墍浠ユ矑鏈夊姞娉ㄩ噴銆?br />

]]>