This repository was archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathutil.py
71 lines (63 loc) · 2.05 KB
/
util.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
#!/usr/bin/python3
#PyVCDS Util script. used to load config files and do per-module logging,
import json
import io
import threading
import inspect
import os
class Config:
def __init__(self, path):
self.lock = threading.Lock()
self.path = None
if not path:
self.backing = None
else:
if not os.path.exists(path):
fd = open(path,"w")
fd.write("{}")
fd.close()
self.open(path)
def __getitem__(self, idx):
if not idx in self.backing:
self.backing[idx] = {}
return self.backing[idx]
def __setitem__(self, idx, item):
with self.lock: #ensures config writes are always consistent among threads
self.backing[idx] = item
self.flush()
def open(self,fname):
self.path = fname #no need to flush, since we do that on every config update
with self.lock:
fd = open(fname,"r")
self.backing = json.loads(fd.read())
fd.close()
def flush(self): #NOTE: do *NOT* add a call to 'self.lock' due to deadlocking with `__setitem__`
fd = open(self.path, "w")
fd.write(json.dumps(self.backing,indent=4))
fd.close()
home = os.environ["HOME"]
assert home, "No home directory? cannot run on windows."
cfgpath = home + "/.pyvcds/config.json"
if not os.path.exists(home + "/.pyvcds"):
os.mkdir(home + "/.pyvcds")
config = Config(cfgpath)
levels = [
"FATAL", #0
"CRITICAL", #1
"ERROR", #2
"WARNING", #3
"INFO", #4
"DEBUG", #5
"TRACE" #6
]
def log(level, *args):
global config
modname = inspect.getmodule(inspect.stack()[1][0]).__name__ #get the calling stack frame, dereference it to the method, then get the module from it.
if not modname in config["log"]:
config["log"][modname] = 4 #initialize the module's log level config to "INFO"
config.flush() #need to manually flush here, since sub-module configs don't trigger our __setitem__ call.
if level <= config["log"][modname]:
if modname == "__main__": #don't include __main__ for module tracing.
print("[{}]".format(levels[level]),*args)
else:
print("[{}] [{}]".format(levels[level],modname),*args)