forked from Peter--K/Sakura
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.py
72 lines (61 loc) · 2.17 KB
/
config.py
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
# -*- coding: utf-8 -*-
import os
import ast
import cfgparse
class Config(object):
def __init__(self):
self.parser = cfgparse.ConfigParser()
cfgfile = self.get_configpath()
print cfgfile
print '==========='
self.cfgfile = cfgfile
try:
open(cfgfile)
except:
# config file not found - create it
path = os.path.dirname(cfgfile)
try:
os.makedirs(path)
except OSError:
if not os.path.isdir(path):
raise
with open(cfgfile, 'w') as f:
print >>f, '[paths]'
print >>f, 'default_dir = ' + os.path.expanduser('~') # Default to home
self.f = self.parser.add_file(cfgfile)
def get_configpath(self):
if 'APPDATA' in os.environ:
confighome = os.environ['APPDATA']
elif 'XDG_CONFIG_HOME' in os.environ:
confighome = os.environ['XDG_CONFIG_HOME']
else:
confighome = os.environ['HOME']
configpath = os.path.join(confighome, '.sakura', 'config.ini')
return configpath
def read_item(self, group, item):
"""Read the item.
Keyword arguments:
group - e.g. 'paths' refers to [paths]
item - e.g. 'save_path'
Returns:
Item value parsed using the Python ast evaluator
"""
option = self.parser.add_option(item, keys=group, type='string')
val = option.get()
try:
val = ast.literal_eval(val)
except (ValueError, SyntaxError):
pass
return val
def write_item(self, group, item, value, item_type='string'):
"""Write the self.config dict to the self.filename ini file
Arguments:
group - e.g. 'paths' refers to [paths]
item - e.g. 'save_path'
value - e.g. r'C:\foo\bar\baz.ini'
item_type - e.g. 'string' (default), 'int'
for types see http://cfgparse.sourceforge.net/cfgparse-option-type.html
"""
option = self.parser.add_option(item, keys=group, type=item_type)
option.set(value)
self.f.write(self.cfgfile)