Last active
December 4, 2018 14:25
-
-
Save dceoy/4628f271df1303304db48c5fa1de0b6b to your computer and use it in GitHub Desktop.
[Python] Generate STDOUT lines from subprocess
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import subprocess | |
def run_and_parse_subprocess(**popen_args): | |
with subprocess.Popen(**popen_args) as p: | |
for line in p.stdout: | |
yield line.decode('utf-8') | |
if p.poll() == 0: | |
pass | |
else: | |
raise subprocess.CalledProcessError( | |
returncode=p.returncode, cmd=p.args, output=p.stdout, | |
stderr=p.stderr | |
) | |
# Example | |
if __name__ == '__main__': | |
sh_args = 'seq 10 | xargs -I {} bash -c "echo -n \\"{}: \\" && date && sleep 1"' | |
for line in run_and_parse_subprocess(args=sh_args, stdout=subprocess.PIPE, | |
shell=True, executable='/bin/bash'): | |
print(line.strip(), flush=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment