#!/usr/bin/env python from subprocess import Popen, PIPE import sys input = """input_data zoological aardvark """ outfile = file('outfile.txt','w') # it blocks if create in left to right order, not sure why! p2 = Popen(['sort'], stdin=PIPE, stdout=outfile) p1 = Popen(['sed', 's/$/ hi there/'], stdin=PIPE, stdout=p2.stdin) p2.stdin.close() # I guess it was dup'd here and in p1 p1.communicate(input) sys.exit(p2.returncode or p1.returncode)