Redirect the output of a command to a string and return it.
(command, argv, extra_args=None)
| 428 | |
| 429 | |
| 430 | def capture_output(command, argv, extra_args=None): |
| 431 | """ |
| 432 | Redirect the output of a command to a string and return it. |
| 433 | """ |
| 434 | if not extra_args: |
| 435 | extra_args = {} |
| 436 | |
| 437 | stdout = sys.stdout |
| 438 | sys.stdout = io.StringIO() |
| 439 | |
| 440 | try: |
| 441 | command(argv, **extra_args) |
| 442 | except Exception as exception: |
| 443 | # Fix stdout in case something goes wrong |
| 444 | sys.stdout = stdout |
| 445 | raise CLIException("Could not get command output: {error}" |
| 446 | .format(error=exception)) |
| 447 | |
| 448 | sys.stdout.seek(0) |
| 449 | output = sys.stdout.read().strip() |
| 450 | sys.stdout = stdout |
| 451 | |
| 452 | return output |
| 453 | |
| 454 | |
| 455 | def exec_command(command, env=None, stdin=None, timeout=None): |