Get CPU utilization (Python calls the top command implementation)
This article locates the situation where you want to call the top command through Python to get CPU usage but have no idea at the moment.
If you simply want to get CPU utilization, the top command redirection can be easily implemented with the following command:
Top-bi > CpuHistory.log or Top-bi | Tee CpuHistory.log
This does not explain, do not understand the friend query top of the help document. What is accomplished here is to call the top command through Python and get the CPU utilization information.
Friends with Popen will soon be able to think of code similar to the following (this is the first time I wrote the Code, *_*):
Os,timetime2sleep = 1.5 True:os.popen (). Read () split () [2] Time.sleep (time2sleep)
The principle seems to be correct, but run up the problem: the idle value of the CPU has been constant!!!
The reason is that the command executed "Top-bi-n 1": Execute this command separately, you will find that the output of the CPU idle value is constant.
So you can't write like this ...
Executing the "Top-bi-n 2" command at the terminal, you will find that the second value changes every time, and this is what we want the results to be.
Given the time, the order would be better: "Top-bi-n 2-d 0.02"
The code is as follows:
#! /usr/bin/python
‘‘‘
File:cpuRate.py
Author:mike
e-mail: [Email protected]
‘‘‘
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 following results are performed:
$./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%st1328109441 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%st1328109444 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%st1328109447 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
This article is from the "World Micro-Dust" blog, please be sure to keep this source http://huangmanyao.blog.51cto.com/12279812/1970095
Get CPU utilization (Python calls the top command implementation)