For a clean version using the subprocess module, you can use the following example ( from the documentation ):
output = `dmesg | grep hda`
becomes
p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output = p2.communicate()[0]
The Python program essentially does what the shell does: it sends the output of each command to the next one in turn. The advantage of this approach is that the programmer has full control over individual standard output errors of commands (they can be suppressed, if necessary, logged, etc.).
However, I prefer to use the subprocess.check_output('ps -ef | grep something | wc -l', shell=True) approach subprocess.check_output('ps -ef | grep something | wc -l', shell=True) to delegate the shell suggested by nneonneo instead: it is generic, very picky, and convenient.
source share