| 1 |
""" |
| 2 |
Utils for Running an external process |
| 3 |
""" |
| 4 |
|
| 5 |
import logging |
| 6 |
import platform |
| 7 |
import shlex |
| 8 |
import subprocess |
| 9 |
import tempfile |
| 10 |
import time |
| 11 |
from collections import namedtuple |
| 12 |
|
| 13 |
log = logging.getLogger(__name__) |
| 14 |
|
| 15 |
ExtCmdResult = namedtuple("ExtCmdResult", "exit_code cmd run_time") |
| 16 |
|
| 17 |
|
| 18 |
def run_cmd(cmd, stdout_fh, stderr_fh, shell=True, |
| 19 |
time_out=None, env=None, executable="/bin/bash"): |
| 20 |
"""Run external command |
| 21 |
|
| 22 |
|
| 23 |
:param: cmd: External command |
| 24 |
:param time_out: Timeout in seconds. |
| 25 |
:type time_out: None | int |
| 26 |
|
| 27 |
:return: ExtCmdResult |
| 28 |
|
| 29 |
This could all be bundled into a context manager |
| 30 |
|
| 31 |
with RunCommand('/path/stdout', '/path/to/stderr') as r: |
| 32 |
r.exe("echo 'exe1') |
| 33 |
r.exe("echo 'exe2') |
| 34 |
result = r.get_result() # close the file handles |
| 35 |
""" |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
started_at = time.time() |
| 43 |
|
| 44 |
if not shell: |
| 45 |
cmd = shlex.split(cmd) |
| 46 |
|
| 47 |
hostname = platform.node() |
| 48 |
log.debug("calling cmd '{c}' on {h}".format(c=cmd, h=hostname)) |
| 49 |
process = subprocess.Popen(cmd, stderr=stderr_fh, stdout=stdout_fh, |
| 50 |
shell=shell, |
| 51 |
executable=executable, |
| 52 |
env=env) |
| 53 |
|
| 54 |
|
| 55 |
max_sleep_time = 5 |
| 56 |
sleep_time = 0.1 |
| 57 |
dt = 0.1 |
| 58 |
|
| 59 |
process.poll() |
| 60 |
while process.returncode is None: |
| 61 |
process.poll() |
| 62 |
time.sleep(sleep_time) |
| 63 |
run_time = time.time() - started_at |
| 64 |
if time_out is not None: |
| 65 |
if run_time > time_out: |
| 66 |
log.warn( |
| 67 |
"Exceeded TIMEOUT of {t}. Killing cmd '{c}'".format( |
| 68 |
t=time_out, c=cmd)) |
| 69 |
try: |
| 70 |
|
| 71 |
process.kill() |
| 72 |
except OSError: |
| 73 |
|
| 74 |
pass |
| 75 |
if sleep_time < max_sleep_time: |
| 76 |
sleep_time += dt |
| 77 |
|
| 78 |
run_time = time.time() - started_at |
| 79 |
returncode = process.returncode |
| 80 |
log.debug("returncode is {r} in {s:.2f} sec.".format(r=process.returncode, |
| 81 |
s=run_time)) |
| 82 |
|
| 83 |
return ExtCmdResult(returncode, cmd, run_time) |