I am using the following command to fetch the CPU usage along with date and time. But I am getting only the CPU usage as output.
My code:
import subprocess
for i in range(3):
cpu = (subprocess.Popen('top -bn2 -d1 | grep "Cpu\|average" ', shell=True, stdout=subprocess.PIPE).stdout)
print(cpu, '----')
output:
%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
Expected Output:
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