utils.py
978 Bytes
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
import json
import sys
if 'esp' in sys.platform:
from urandom import getrandbits
else:
import random
def save_object_to_file(obj, filename):
with open(filename, 'w', encoding='utf-8') as f:
f.write(json.dumps(obj))
def load_object_from_file(filename):
try:
with open(filename, 'r', encoding='utf-8') as f:
return json.loads(f.read())
except Exception as e:
print('Error opening file: ' + filename)
print(e)
return None
def randrange(start, stop=None):
if 'esp' in sys.platform:
if start == 1:
return 0
if stop is None:
stop = start
start = 0
upper = stop - start
bits = 0
pwr2 = 1
while upper > pwr2:
pwr2 <<= 1
bits += 1
while True:
r = getrandbits(bits)
if r < upper:
break
return r + start
else:
return random.randrange(start)