forked from ross-g/io_pdx_mesh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
settings.py
76 lines (62 loc) · 2.3 KB
/
settings.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
"""
IO PDX Mesh Python module.
Simple settings object which writes to a JSON file on any value being set.
author : ross-g
"""
import os
import sys
import json
import logging
import os.path as path
SETTINGS_LOG = logging.getLogger("io_pdx.settings")
""" ====================================================================================================================
Module settings class.
========================================================================================================================
"""
class PDXsettings(object):
def __init__(self, filepath):
if path.exists(filepath):
# read settings file
self.load_settings_file(filepath)
else:
# new settings file
try:
os.makedirs(path.dirname(filepath))
with open(filepath, "w") as _:
pass
except OSError:
SETTINGS_LOG.error("Failed creating new settings file", exc_info=True)
# default settings
self.config_path = filepath
self.config_dir = path.dirname(filepath)
self.app = sys.executable
def __setattr__(self, name, value):
result = super(PDXsettings, self).__setattr__(name, value)
self.save_settings_file()
return result
def __getattr__(self, attr):
try:
return super(PDXsettings, self).__getattr__(attr)
except AttributeError:
return None
def __delattr__(self, name):
result = super(PDXsettings, self).__delattr__(name)
self.save_settings_file()
return result
def load_settings_file(self, filepath):
# default to empty settings dictionary
settings_dict = {}
with open(filepath) as f:
try:
settings_dict = json.load(f)
except Exception:
SETTINGS_LOG.error("Failed loading settings file", exc_info=True)
self.config_path = filepath
for k, v in settings_dict.items():
setattr(self, k, v)
def save_settings_file(self):
try:
with open(self.config_path, "w") as f:
json.dump(self.__dict__, f, sort_keys=True, indent=4)
except Exception:
SETTINGS_LOG.error("Failed saving settings file", exc_info=True)