This article locates the situation where you want to call the top command in Python to get CPU usage but there is no idea for the moment.
If you simply want to get CPU utilization, you can easily do this by using the top command redirection, which commands the following:
Copy Code code as follows:
Or
Copy Code code as follows:
Top-bi | Tee CpuHistory.log
This does not explain, do not understand the friend query the top of the help document. The implementation here is to call the top command through Python and get CPU utilization information.
Friends who have used Popen will soon be able to think of code similar to the following (this is the first time I wrote the Code, *_*):
Copy Code code as follows:
#! /usr/bin/python
Import Os,time
Time2sleep = 1.5
While True:
Print Os.popen (' Top-bi-n 1 '). Read (). split (' \ n ') [2]
Time.sleep (Time2sleep)
The principle looks right, but running up is a problem: The CPU idle value has been unchanged!!!
The reason is the command "Top-bi-n 1": Execute this command individually, you will find that the idle value of the CPU in the output is constant.
So it can't be written ...
At the end of the "Top-bi-n 2" command, you will find that the second value changes every time, this is what we want the results.
Given the time, the command would be better to write: "Top-bi-n 2-d 0.02".
The code is as follows:
Copy Code code as follows:
#! /usr/bin/python
'''
File:cpuRate.py
Author:mike
E-mail:mike_zhang@live.com
'''
Import Os,time
Time2sleep = 2.5
While True:
print int (time.time ()),
Print Os.popen (' top-bi-n 2-d 0.02 '). Read (). Split (' \n\n\n ') [1].split (' \ n ') [2]
Time.sleep (Time2sleep)
The execution effect is as follows:
Copy Code code as follows:
$./cpurate.py
1328109437 Cpu (s): 10.0%us, 20.0%sy, 0.0%ni, 70.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
1328109441 Cpu (s): 0.0%us, 16.7%sy, 0.0%ni, 83.3%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
1328109444 Cpu (s): 0.0%us, 16.7%sy, 0.0%ni, 83.3%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
1328109447 Cpu (s): 12.5%us, 12.5%sy, 0.0%ni, 75.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Well, that's all, I hope to help you.