forked from juju/juju
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
51 lines (38 loc) · 1.08 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
from contextlib import contextmanager
from datetime import datetime
import random
import shutil
import string
from tempfile import mkdtemp
@contextmanager
def temp_dir():
dirname = mkdtemp()
try:
yield dirname
finally:
shutil.rmtree(dirname)
class until_timeout:
"""Yields remaining number of seconds. Stops when timeout is reached.
:ivar timeout: Number of seconds to wait.
"""
def __init__(self, timeout, start=None):
self.timeout = timeout
if start is None:
start = self.now()
self.start = start
def __iter__(self):
return self
@staticmethod
def now():
return datetime.now()
def next(self):
elapsed = self.now() - self.start
remaining = self.timeout - elapsed.total_seconds()
if remaining <= 0:
raise StopIteration
return remaining
def get_random_hex_string(size=64):
return ''.join(random.choice(string.hexdigits) for n in range(size))
def write_file(path, contents):
with open(path, 'w') as f:
f.write(contents)