def pipeline(*pipe_cmds, **kw): # Backup stdout, as it is for the last process in the pipeline only stdout = kw.get('stdout') # We're building first stages of the pipeline connected together kw['stdout'] = PIPE for cmd in pipe_cmds[:-1]: p = Popen(cmd, **kw) kw['stdin'] = p.stdout handles.append(p) # Restore backuped stdout for the last stage kw['stdout'] = stdout # End of the pipeline handled manually since we cannot reassign # p.stdout after Popen() call return Popen(pipe_cmds[-1], **kw) pipeline(["/bin/ls"], ["/usr/bin/wc", "-l"]).communicate()