-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
45 lines (36 loc) · 1021 Bytes
/
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
import secrets
import string
import hashlib
import signal
import time
from contextlib import contextmanager
def generate_secure_string(N):
return ''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(N))
def hash_file(file, block_size=65536):
hasher = hashlib.md5()
while True:
data = file.read(block_size)
if not data:
break
hasher.update(data)
return hasher.hexdigest()
# Reference: https://stackoverflow.com/a/601168
class TimeoutException(Exception): pass
@contextmanager
def time_limit(seconds, message="Time limit exceeded"):
if seconds:
def signal_handler(signum, frame):
raise TimeoutException(message)
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(seconds)
try:
yield
finally:
signal.alarm(0)
@contextmanager
def time_print(task_name):
t = time.time()
try:
yield
finally:
print(task_name, "took", time.time() - t, "seconds.")