Skip to content

Instantly share code, notes, and snippets.

@samuell
Created February 16, 2015 21:56
Show Gist options
  • Save samuell/9f2397ac3ddcf6946bbc to your computer and use it in GitHub Desktop.
Save samuell/9f2397ac3ddcf6946bbc to your computer and use it in GitHub Desktop.
Parse a shell command with pipe characters, into a subprocess chain
import subprocess as sub
def create_pipes(cmd):
procs = {}
parts = cmd.split('|')
for i, part in enumerate(parts):
cmdparts = part.strip().split(' ')
if i == 0:
procs[i] = sub.Popen(cmdparts, stdout=sub.PIPE)
else:
procs[i] = sub.Popen(cmdparts, stdin=procs[i-1].stdout, stdout=sub.PIPE)
print procs[len(procs)-1].communicate()[0]
for proc in procs.values():
proc.stdout.close()
if __name__ == '__main__':
create_pipes("echo hej | tr 'e' 'a' | tee out.log")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment