forked from joefutrelle/oii
/
procutil.py
42 lines (40 loc) · 1.33 KB
/
procutil.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
from oii.times import iso8601ms
from oii.utils import gen_id
from subprocess import Popen, PIPE
def timestamped_output_of(cmd,stdout=True,jobid=None):
issued = iso8601ms()
if jobid is None:
jobid = gen_id()
def log_struct(message):
return {
'command': cmd,
'issued': issued,
'jobid': jobid,
'message': message,
'timestamp': iso8601ms()
}
yield log_struct('executing shell command %s, jobid %s' % (cmd,jobid))
if stdout:
p = Popen(cmd, shell=True, stdout=PIPE)
else:
p = Popen(cmd, shell=True, stderr=PIPE)
while True:
if stdout:
line = p.stdout.readline()
else:
line = p.stderr.readline()
if not line:
p.wait()
if p.returncode != 0:
message = 'process exited abnormally with exit code %d: %s' % (p.returncode, cmd)
yield log_struct(message)
raise RuntimeError(message)
yield log_struct('process closed output stream: '+cmd)
return
yield log_struct(line.rstrip('\n'))
class Process(object):
def __init__(self,command):
self.command = command
def run(self,params={}):
for log_msg in timestamped_output_of(self.command % params):
yield log_msg