使用python子进程取消打包以使用管道从grep获取输出

时间:2019-11-08 07:41:54

标签: python

我正在使用以下命令来获取CPU使用率以及日期和时间。但是我只获得CPU使用率作为输出。

我的代码:

import subprocess
for i in range(3):
    cpu = (subprocess.Popen('top -bn2 -d1 | grep "Cpu\|average" ', shell=True, stdout=subprocess.PIPE).stdout)
    print(cpu, '----')

输出:

  %Cpu(s):  7.3 us,  1.2 sy,  0.1 ni, 88.8 id,  2.5 wa,  0.0 hi,  0.1 si,  0.0 st
  %Cpu(s):  1.5 us,  0.2 sy,  0.0 ni, 98.3 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
  --------
  %Cpu(s):  7.3 us,  1.2 sy,  0.1 ni, 88.8 id,  2.5 wa,  0.0 hi,  0.1 si,  0.0 st
  %Cpu(s):  2.7 us,  1.0 sy,  0.0 ni, 93.8 id,  2.5 wa,  0.0 hi,  0.0 si,  0.0 st
  --------
  %Cpu(s):  7.3 us,  1.2 sy,  0.1 ni, 88.8 id,  2.5 wa,  0.0 hi,  0.1 si,  0.0 st
  %Cpu(s):  3.8 us,  0.5 sy,  0.0 ni, 95.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st

预期输出:

 top - 12:58:07 up  2:37,  1 user,  load average: 0.61, 0.72, 0.58
  %Cpu(s):  7.3 us,  1.2 sy,  0.1 ni, 88.9 id,  2.5 wa,  0.0 hi,  0.1 si,  0.0 st
  top - 12:58:08 up  2:37,  1 user,  load average: 0.61, 0.72, 0.58
  %Cpu(s): 12.7 us,  2.0 sy,  0.0 ni, 78.3 id,  7.0 wa,  0.0 hi,  0.0 si,  0.0 st

2 个答案:

答案 0 :(得分:1)

像这样添加read()decode(),您将拥有所需的内容。

import subprocess
for i in range(3):
    cpu = (subprocess.Popen('top -bn2 -d1 | grep "Cpu\|average" ', shell=True, stdout=subprocess.PIPE).stdout)
    print(cpu.read().decode('utf-8'), '\n----')    

输出:

top - 15:43:00 up  7:36,  1 user,  load average: 0,97, 0,95, 1,28
%Cpu(s): 12,4 us,  3,1 sy,  0,0 ni, 84,1 id,  0,0 wa,  0,0 hi,  0,3 si,  0,0 st
top - 15:43:01 up  7:36,  1 user,  load average: 0,97, 0,95, 1,28
%Cpu(s):  5,9 us,  1,5 sy,  0,0 ni, 92,5 id,  0,0 wa,  0,0 hi,  0,2 si,  0,0 st

----
top - 15:43:01 up  7:36,  1 user,  load average: 0,97, 0,95, 1,28
%Cpu(s): 12,4 us,  3,1 sy,  0,0 ni, 84,1 id,  0,0 wa,  0,0 hi,  0,3 si,  0,0 st
top - 15:43:02 up  7:36,  1 user,  load average: 0,89, 0,94, 1,27
%Cpu(s):  2,1 us,  0,8 sy,  0,0 ni, 96,9 id,  0,0 wa,  0,0 hi,  0,2 si,  0,0 st

----
top - 15:43:02 up  7:36,  1 user,  load average: 0,89, 0,94, 1,27
%Cpu(s): 12,4 us,  3,1 sy,  0,0 ni, 84,1 id,  0,0 wa,  0,0 hi,  0,3 si,  0,0 st
top - 15:43:03 up  7:36,  1 user,  load average: 0,89, 0,94, 1,27
%Cpu(s):  4,1 us,  0,8 sy,  0,0 ni, 94,9 id,  0,0 wa,  0,0 hi,  0,2 si,  0,0 st

----

答案 1 :(得分:0)

stdout的输出为BufferedReader类型,您需要添加.read()方法或.communicate()以获得正确的字符串输出,例如:

cpu = (subprocess.Popen('top -bn2 -d1 | grep "Cpu\|average" ', shell=True, stdout=subprocess.PIPE).stdout).read()

或使用通讯(在这里您还会得到错误)

cpu, err = subprocess.Popen('top -bn2 -d1 | grep "Cpu\|average" ', shell=True, stdout=subprocess.PIPE).communicate()

这是输出:

print(cpu.decode('utf-8'))
'top - 14:22:27 up  4:24,  1 user,  load average: 1.40, 1.72, 1.80\n%Cpu(s): 12.6 us,  3.2 sy,  1.8 ni, 59.9 id, 22.3 wa,  0.0 hi,  0.2 si,  0.0 st\ntop - 14:22:28 up  4:24,  1 user,  load average: 1.45, 1.72, 1.80\n%Cpu(s):  3.0 us,  2.5 sy,  0.0 ni, 83.6 id, 10.9 wa,  0.0 hi,  0.0 si,  0.0 st\n'

有关文档的更多信息:here