-
Notifications
You must be signed in to change notification settings - Fork 49
/
toolutils.py
35 lines (28 loc) · 946 Bytes
/
toolutils.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
import os
import tempfile
import shutil
from contextlib import contextmanager
import subprocess
def safe_subprocess(command_array):
''' return True/False, command output '''
try:
return True, subprocess.Popen(command_array,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT).communicate()[0]
except OSError as e:
return False, e.__str__()
except subprocess.CalledProcessError as e:
return False, e.output
@contextmanager
def atomic_write(filepath):
"""
Writeable file object that atomically
updates a file (using a temporary file).
:param filepath: the file path to be opened
"""
with tempfile.NamedTemporaryFile() as tf:
with open(tf.name, mode='w+') as tmp:
yield tmp
tmp.flush()
os.fsync(tmp.fileno())
shutil.copy(tf.name, filepath)