Running shell command in python and reading output
Question: I have the following:

    
    
    cmd = "ps aux | grep 'java -jar' | grep -v grep | awk '//{print $2}'".split(' ')
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()
    print out
    

When I run the command in the console (outside of python), I get the desired
output. Running this above code in python prints a blank line. I am assuming
there is something up with the `cmd` (specifically the `|` operator) but I
can't be sure.

I need to achieve this with the standard Python 2.6.6 install (no additional
modules)


Answer: You need to use a single call to `Popen()` for each piece of the original
command, as connected by the pipe, as in

    
    
    import subprocess
    
    p1 = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE,  stderr=subprocess.PIPE)
    p2 = subprocess.Popen(["grep", "java -jar"], stdin=p1.stdout, stdout=subprocess.PIPE,  stderr=subprocess.PIPE)
    p3 = subprocess.Popen(["grep", "-v", "grep"], stdin=p2.stdout, stdout=subprocess.PIPE,  stderr=subprocess.PIPE)
    p4 = subprocess.Popen(["awk", "//{print $2}"], stdin=p3.stdout, stdout=subprocess.PIPE,  stderr=subprocess.PIPE)
    out, err = p4.communicate()
    
    print out
    

The [subprocess
documentation](https://docs.python.org/2/library/subprocess.html#replacing-
shell-pipeline) has an in-depth discussion.

