-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxeeTools.py
More file actions
executable file
·184 lines (146 loc) · 4.94 KB
/
xeeTools.py
File metadata and controls
executable file
·184 lines (146 loc) · 4.94 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#!/usr/bin/env python3
"""A module holding some functions frequently used by me."""
from functools import wraps
from pprint import pprint
import inspect
import sys
import time
import traceback
################################################################################
def dd(*data):
"""Helper for fast debug view of each kind of data.
Inspirated by Laravel's dd() function."""
print()
print(100 * "=")
# get the caller's metadata: class and method
print()
print("Output of dd(), ", end="")
# check if in class context
stack = inspect.stack()
if "self" in stack[1][0].f_locals:
the_class = str(stack[1][0].f_locals["self"].__class__)
the_class = the_class.split("'")[1]
the_method = stack[1][0].f_code.co_name
print("called by:")
print(f"{str(the_class)}.{the_method}()")
else:
print("called from")
# get the caller's metadata: file and line
tb = traceback.extract_stack(limit=2)
print(f"{tb[0][0]}, line {tb[0][1]}")
print()
# pretty print all given data
for i, d in enumerate(data):
print()
print(80 * "=")
print()
the_type = f"Argument {i} is of type {type(d)}"
print(the_type)
print(len(the_type) * "-")
pprint(d)
print()
print()
print(100 * "=")
print()
print()
# Exit with error to indicate non standard execution
sys.exit(1)
################################################################################
def ex_to_str(ex):
"""Converts an exception to a human readable string containing relevant informations.
Use e.g. to create meaningful log entries."""
# get type and message of risen exception
ex_type = f"{type(ex).__name__}"
ex_args = ", ".join(map(str, ex.args)) # may contain e.g. ints
# get the command where the exception has been raised
tb = traceback.extract_tb(sys.exc_info()[2], limit=2)
ex_cmd = tb[0][3]
ex_file = tb[0][0]
ex_line = tb[0][1]
# the string (one liner) to return
nice_ex = f"{ex_type} ({ex_args}) raised executing '{ex_cmd}' in {ex_file}, line {ex_line}"
return nice_ex
################################################################################
def seconds_to_timestring(seconds):
hours = int(seconds // 3600)
seconds %= 3600
minutes = int(seconds // 60)
seconds = round(seconds % 60)
return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
################################################################################
def info(msg):
if sys.platform.startswith("linux"):
msg = "\033[1;38;5;32m" + msg + "\033[0m"
print(msg)
################################################################################
def success(msg):
if sys.platform.startswith("linux"):
msg = "\033[1;38;5;46m" + msg + "\033[0m"
print(msg)
################################################################################
def warning(msg):
if sys.platform.startswith("linux"):
msg = "\033[1;38;5;184m" + msg + "\033[0m"
print(msg)
################################################################################
def error(msg):
if sys.platform.startswith("linux"):
msg = "\033[1;38;5;196m" + msg + "\033[0m"
print(msg)
################################################################################
def timeit(func):
"""
Decorator to print how long a function was running.
"""
@wraps(func) # needed to get func.__qualname__ of the wrapped function
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
result = func(*args, **kwargs)
end_time = time.perf_counter()
runtime = end_time - start_time
print(f"Function “{func.__qualname__}()” finished in {runtime:.4f} seconds.")
return result
return wrapper
@timeit
def _run_one_sec():
time.sleep(1)
################################################################################
################################################################################
################################################################################
if __name__ == "__main__":
# test the exception converter
print()
print(80 * "#")
print("Testing exception")
print()
try:
a = 3 - 3
b = 1 / a
c = a + b
except Exception as ex:
print(ex_to_str(ex))
# raise
# test the exception converter
print()
print(80 * "#")
print("Testing exception having int inside the tupel")
print()
try:
with open(
"dac725e6-47ca-46de-80e7-a78d9a136129/0a2ec5b6-779d-4df4-a83f-1aabeac9f931"
) as fh:
pass
except Exception as ex:
print(ex_to_str(ex))
print()
print(80 * "#")
print("Testing timeit() decorator")
print()
_run_one_sec()
# test dd last because it ends the script :-)
print()
print(80 * "#")
print("Testing dd()")
print()
l = ["foo", "bar", 42]
dd("test", l)