-
Notifications
You must be signed in to change notification settings - Fork 8
/
utils.py
91 lines (70 loc) · 2.43 KB
/
utils.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import config, os, json
def locate_setting_folder():
"""check local folder and global setting folder for setting.cfg file"""
# look for previous setting file
try:
if 'setting.cfg' in os.listdir(config.current_directory):
return config.current_directory
except:
pass
# no setting file found will check local folder for writing permission, otherwise will return global sett folder
try:
folder = config.current_directory
with open(os.path.join(folder, 'test'), 'w') as test_file:
test_file.write('0')
os.unlink(os.path.join(folder, 'test'))
return config.current_directory
except PermissionError:
log("No enough permission to store setting at local folder:", folder)
config.sett_folder = locate_setting_folder()
def to_command_paras(username, password):
str_paras = ""
str_paras += ' -u ' + username
str_paras += ' -p ' + password
return str_paras
def load_setting():
settings = {}
try:
log('Load Application setting from', config.sett_folder)
file = os.path.join(config.sett_folder, 'setting.cfg')
with open(file, 'r') as f:
settings = json.load(f)
except FileNotFoundError:
log('setting.cfg not found')
except Exception as e:
handle_exceptions(e)
finally:
if not isinstance(settings, dict):
settings = {}
# update config module
config.__dict__.update(settings)
def save_setting():
settings = {key: config.__dict__.get(key) for key in config.settings_keys}
try:
file = os.path.join(config.sett_folder, 'setting.cfg')
with open(file, 'w') as f:
json.dump(settings, f)
log('setting saved')
except Exception as e:
log('save_setting() > error', e)
def handle_exceptions(error):
if config.TEST_MODE:
raise error
else:
log(error)
def log(*args, start='>> ', end='\n', sep=' '):
"""
print messages to stdout and log widget in main menu thru main window queue
:param args: comma separated messages to be printed
:param start: prefix appended to start of string
:param end: tail of string
:param sep: separator used to join text "args"
:return:
"""
text = ''
for arg in args:
text += str(arg)
text += sep
text = text[:-1] # remove last space, or sep
text = start + text
print(text, end=end)