使用“|”执行子进程时出错

时间:2015-07-29 20:31:37

标签: python format subprocess

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

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

进入一个termianl我收到回复:

%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

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

1 个答案:

答案 0 :(得分:3)

您需要使用from subprocess import check_output out = check_output("ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10",shell=True,stderr=STDOUT) 来使用竖线字符,如果您要沿着该路线走下去,那么使用check_output将是获取输出的最简单方法:

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

您还可以使用Popen和shell = False模拟管道,例如:

101