Created
August 9, 2018 14:12
-
-
Save depp/c798381d6810657f528fe8d0d8013729 to your computer and use it in GitHub Desktop.
Simple command piping in Python
This file contains hidden or 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
# 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