Skip to content Skip to sidebar Skip to footer

Error Is Being Raised When Executing A Sub-process Using " | "

I am trying to automate the process of executing a command. When I this command: ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10 Into a termianl I get the response: %CPU PID

Solution 1:

You would need to use shell=True to use the pipe character, if you are going to go down that route then using check_output would be the simplest approach to get the output:

from subprocess import check_output

out = check_output("ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10",shell=True,stderr=STDOUT)

You can also simulate a pipe with Popen and shell=False, something like:

from subprocess import Popen, PIPE, STDOUT
sshcmd = Popen(['ps', '-eo', "pcpu,pid,user,args"],
               stdout=PIPE,
               stderr=STDOUT)
p2 = Popen(["sort", "-k", "1", "-r"], stdin=sshcmd.stdout, stdout=PIPE)
sshcmd.stdout.close()
p3 = Popen(["head", "-10"], stdin=p2.stdout, stdout=PIPE,stderr=STDOUT)
p2.stdout.close()
out, err = p3.communicate()

Post a Comment for "Error Is Being Raised When Executing A Sub-process Using " | ""