Skip to content

Instantly share code, notes, and snippets.

@dceoy
Last active December 4, 2018 14:25
Show Gist options
  • Save dceoy/4628f271df1303304db48c5fa1de0b6b to your computer and use it in GitHub Desktop.
Save dceoy/4628f271df1303304db48c5fa1de0b6b to your computer and use it in GitHub Desktop.
[Python] Generate STDOUT lines from subprocess
#!/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