Execute command.
(command, env=None, stdin=None, timeout=None)
| 453 | |
| 454 | |
| 455 | def exec_command(command, env=None, stdin=None, timeout=None): |
| 456 | """ |
| 457 | Execute command. |
| 458 | """ |
| 459 | process = subprocess.Popen( |
| 460 | command, |
| 461 | stdin=stdin, |
| 462 | stdout=subprocess.PIPE, |
| 463 | stderr=subprocess.PIPE, |
| 464 | env=env, |
| 465 | universal_newlines=True) |
| 466 | |
| 467 | try: |
| 468 | stdout, stderr = process.communicate(timeout=timeout) |
| 469 | except subprocess.TimeoutExpired as exception: |
| 470 | # The child process is not killed if the timeout expires, so in order |
| 471 | # to cleanup properly a well-behaved application should kill the child |
| 472 | # process and finish communication. |
| 473 | # https://docs.python.org/3.5/library/subprocess.html |
| 474 | process.kill() |
| 475 | stdout, stderr = process.communicate() |
| 476 | raise CLIException("Timeout expired: {error}".format(error=exception)) |
| 477 | |
| 478 | return (process.returncode, stdout, stderr) |
| 479 | |
| 480 | |
| 481 | def popen_tty(cmd, shell=True): |