Skip to content

Instantly share code, notes, and snippets.

@depp
Created August 9, 2018 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save depp/c798381d6810657f528fe8d0d8013729 to your computer and use it in GitHub Desktop.
Save depp/c798381d6810657f528fe8d0d8013729 to your computer and use it in GitHub Desktop.
Simple command piping in Python
# https://stackoverflow.com/questions/51756938/how-to-make-a-generic-method-in-python-to-execute-multiple-piped-shell-commands
import shlex
import subprocess
def run_pipe(cmds):
pipe = subprocess.DEVNULL
procs = []
for cmd in cmds:
proc = subprocess.Popen(cmd, stdin=pipe, stdout=subprocess.PIPE)
procs.append(proc)
pipe = proc.stdout
stdout, _ = proc.communicate()
for proc in procs:
proc.wait()
for proc in procs:
if proc.returncode:
raise subprocess.CalledProcessError(proc.returncode, proc.cmd)
return stdout
def run_pipe_text(cmds):
return run_pipe([shlex.split(cmd) for cmd in cmds.split('|')])
if __name__ == "__main__":
print(run_pipe_text("echo abcd | tr ac __"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment