-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
80 lines (53 loc) · 1.59 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
import json
import os
import os.path as p
from datetime import datetime
from box import Box
import logging as log
log.basicConfig(level=log.INFO)
def get_str_or_box(content_str, filename):
if filename.endswith('.json') and content_str:
ret = Box(json.loads(content_str))
else:
ret = content_str
return ret
def write_json(obj, path):
with open(path, 'w') as f:
json.dump(obj, f, indent=2)
def read_json(filename):
with open(filename) as file:
results = json.load(file)
return results
def write_file(content, path):
with open(path, 'w') as f:
f.write(content)
def read_file(path):
with open(path) as f:
ret = f.read()
return ret
def read_lines(path):
content = read_file(path)
lines = content.split()
return lines
def append_file(path, strings):
with open(path, 'a') as f:
f.write('\n'.join(strings) + '\n')
def exists_and_unempty(problem_filename):
return p.exists(problem_filename) and os.stat(problem_filename).st_size != 0
def is_docker():
path = '/proc/self/cgroup'
return (
os.path.exists('/.dockerenv') or
os.path.isfile(path) and any('docker' in line for line in open(path))
)
def generate_rand_alphanumeric(num_chars):
from secrets import choice
import string
alphabet = string.ascii_lowercase + string.digits
ret = ''.join(choice(alphabet) for _ in range(num_chars))
return ret
def get_sortable_time_string():
ret = datetime.utcnow().strftime('%Y-%m-%d_%I-%M-%S%p')
return ret
def dbox(obj):
return Box(obj, default_box=True)