config_file.py
directory : D:\2018_py_proj\TkGridGUI\tkgridgui
Line Count : 190
Line Clip Size : No Clipping
tab_of_notebook_changed Word MatchCase (0)
1
2
3 from __future__ import print_function
4 from __future__ import unicode_literals
5
6 from future import standard_library
7 standard_library.install_aliases()
8 from builtins import range
9 from builtins import object
10 from builtins import str
11
12 r"""
13 ConfigFile wraps a configparser file as an in-memory container with a few
14 more options.
15
16 such as:
17 mycfg['BadNews','IQ'] = 'very low'
18 x = mycfg['BadNews','IQ']
19 del mycfg['BadNews','IQ']
20 mycfg.save_file()
21 myDict = mycfg.get_dictionary()
22
23 Save to file can be triggered by a "has_changes" flag.
24
25
26 ConfigFile
27 Copyright (C) 2015 Charlie Taylor
28
29 This program is free software: you can redistribute it and/or modify
30 it under the terms of the GNU General Public License as published by
31 the Free Software Foundation, either version 3 of the License, or
32 (at your option) any later version.
33
34 This program is distributed in the hope that it will be useful,
35 but WITHOUT ANY WARRANTY; without even the implied warranty of
36 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37 GNU General Public License for more details.
38
39 You should have received a copy of the GNU General Public License
40 along with this program. If not, see <http://www.gnu.org/licenses/>.
41
42 -----------------------
43
44 """
45
46
47
48 __author__ = 'Charlie Taylor'
49 __copyright__ = 'Copyright (c) 2013 Charlie Taylor'
50 __license__ = 'GPL-3'
51 __version__ = '0.1.1'
52 __email__ = "cet@appliedpython.com"
53 __status__ = "Development"
54
55
56
57 import sys
58 import os
59 import configparser
60 from configparser import NoOptionError, NoSectionError
61
62 class ConfigInterface(object):
63 """ConfigFile wraps a configparser file as an in-memory container
64 """
65
66 def __init__(self, config_filename='myconfig.cfg', sectionL=None):
67 """Inits ConfigInterface a ConfigParser and a config file name.
68
69 :param config_filename: name of config file (data files also in config format)
70 :param sectionL: a list of section headings in config file
71
72 :type config_filename: string
73 :type sectionL: list of strings
74 """
75 self.has_changes = False
76 self.state_id_number = 0
77
78 self.config_filename= os.path.abspath( config_filename )
79
80 if config_filename.lower().endswith('.cfg'):
81 print( 'Config File:', self.config_filename )
82 else:
83 print( 'Data File:', self.config_filename )
84
85
86 self.config = configparser.RawConfigParser()
87 self.config.optionxform = str
88
89 if os.path.isfile(self.config_filename):
90 self.config.read(self.config_filename)
91 self.config_files_first_open = False
92 else:
93 self.config_files_first_open = True
94
95 if sectionL:
96 for section in sectionL:
97 if not self.config.has_section( section ):
98 self.config.add_section(section)
99 self.has_changes = True
100 self.state_id_number += 1
101
102 def get_sectionL(self):
103 """Return a list of all sections in config file"""
104 return self.config.sections()
105
106 def get_optionL(self, section):
107 """Return a list of options for section in config file"""
108 return self.config.options(section)
109
110 def get_dictionary(self):
111 """Make a dictionary representation of config file"""
112 D = {}
113 for section in self.config.sections():
114 sectD = {}
115 for option in self.config.options(section):
116 sectD[option] = self.config.get(section, option)
117 D[section] = sectD
118
119 return D
120
121
122 def set(self, section, option, value):
123 """Calls configparser set method and sets self.has_changes=True"""
124 if not self.config.has_section( section ):
125 self.config.add_section(section)
126
127 self.config.set(section, option, value)
128 self.has_changes = True
129 self.state_id_number += 1
130
131 def has_section(self, section):
132 """Calls configparser has_section method"""
133 return self.config.has_section(section)
134
135 def has_option(self, section, option):
136 """Calls configparser has_section method"""
137 return self.config.has_option(section, option)
138
139 def save_file(self):
140 """Saves self.config to self.config_filename
141 Also sets self.has_changes=False
142 """
143 with open(self.config_filename, 'w') as configfile:
144 self.config.write( configfile )
145
146
147 self.has_changes = False
148
149 def delete_file(self):
150 """Deletes self.config_filename"""
151 if os.path.isfile( self.config_filename ):
152 os.remove( self.config_filename )
153
154 def __getitem__(self, key_tup):
155 """Allows data access such as:
156 mycfg['BadNews','IQ']
157 """
158 if len(key_tup)==2:
159 section, option = key_tup
160 try:
161 return self.config.get(section, option)
162 except (NoOptionError, NoSectionError):
163 return None
164
165 def __setitem__(self, key_tup, value):
166 """Allows assignments such as:
167 mycfg['BadNews','IQ'] = 'very low'
168 (changes self.has_changes to True as a side-effect)
169 """
170 if len(key_tup)==2:
171 section, option = key_tup
172 self.set(section, option, value)
173
174 def __delitem__(self, key_tup):
175 """Allows removal of item as:
176 del mycfg['BadNews','IQ']
177 (changes self.has_changes to True as a side-effect)
178 """
179 if len(key_tup)==2:
180 section, option = key_tup
181 try:
182 self.state_id_number += 1
183 self.config.remove_option(section, option)
184 self.has_changes = True
185 except (NoOptionError, NoSectionError):
186 pass
187
188
189 if __name__ == '__main__':
190 C = ConfigInterface()
191