使用“|”执行子流程时出现错误

Error is being raised when executing a sub-process using " | "

我正在尝试使执行命令的过程自动化。当我这个命令时:

ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10

进入终端我得到响应:

%CPU   PID USER     COMMAND
 5.7 25378 stackusr whttp
 4.8 25656 stackusr tcpproxy

但是当我执行这部分代码时,我收到关于格式说明符的错误:

  if __name__ == '__main__':
        fullcmd = ['ps','-eo','pcpu,pid,user,args | sort -k 1 -r | head -10']
        print fullcmd
        sshcmd = subprocess.Popen(fullcmd,
                    shell= False,
                    stdout= subprocess.PIPE,
                    stderr= subprocess.STDOUT)
        out = sshcmd.communicate()[0].split('\n')
        #print 'here'
        for lin in out:
            print lin

这是显示的错误:

ERROR: Unknown user-defined format specifier "|".
********* simple selection *********  ********* selection by list *********
-A all processes                      -C by command name
-N negate selection                   -G by real group ID (supports names)
-a all w/ tty except session leaders  -U by real user ID (supports names)
-d all except session leaders         -g by session OR by effective group name
-e all processes                      -p by process ID
T  all processes on this terminal     -s processes in the sessions given
a  all w/ tty, including other users  -t by tty
g  OBSOLETE -- DO NOT USE             -u by effective user ID (supports names)
r  only running processes             U  processes for specified users
x  processes w/o controlling ttys     t  by tty

我试过在 | 之前放置一个 \但这没有效果。

您需要使用 shell=True 来使用竖线字符,如果您要沿着这条路线走下去,那么使用 check_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)

你也可以用 Popen 和 shell=False 来模拟一个管道,比如:

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()