如何在不使用 PSUtil 的情况下在 python 2.7 中使用 CPU
How to get CPU usage in python 2.7 without using PSUtil
尝试在不使用 PSUtil
的情况下在 Python
中使用 CPU。
我尝试了以下方法,但似乎总是报告相同的数字...
def getCPUuse():
return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print }'").readline().strip(\
)))
print(getCPUuse())
这似乎总是报告 3.7%,即使我加载 CPU。
我也试过以下...
str(round(float(os.popen('''grep 'cpu ' /proc/stat | awk '{usage=(+)*100/(++)} END {print usage }' ''').readline()),2))
这似乎总是return 5.12。必须承认我真的不知道上面的内容。如果我在命令行中输入 grep cpu /proc/stat
我会得到类似这样的东西...
cpu 74429 1 19596 1704779 5567 0 284 0 0 0
cpu0 19596 0 4965 422508 1640 0 279 0 0 0
cpu1 18564 1 4793 427115 1420 0 1 0 0 0
cpu2 19020 0 4861 426916 1206 0 2 0 0 0
cpu3 17249 0 4977 428240 1301 0 2 0 0 0
我猜我的命令没有正确地从上面的输出中提取我所有 CPU 核心的值?
我的 objective 是在不使用 PSUtil 的情况下从我的设备 (Raspberry PI) 中获取总计 CPU %。该图应反映 OS 任务管理器中显示的内容。
这并不容易,因为您描述的大部分过程都提供 CPU 使用情况的累积或总平均值。
也许你可以尝试使用 systat
包自带的 mpstat
命令。
因此,我用于以下脚本的步骤是:
- 要求
mpstat
生成 2 份报告,一份立即生成,一份在 1 秒后生成 (mpstat 1 2
)
- 然后我们得到
Average
行(最后一行)
- 最后一列是
%idle
列,因此我们使用 awk
中的 $NF
变量得到它
- 我们使用子进程中的
Popen
,但设置 shell=True
以接受我们的管道 (|
) 选项。
- 我们执行命令(
communicate()
)
- 使用
strip
清理输出
- 然后从 100 中减去(闲置百分比),这样我们就可以得到已使用的值。
因为它会休眠 1 second
,所以不用担心它不是 instant 命令。
import subprocess
cmd = "mpstat 1 2 | grep Average | awk '{print $NF}'"
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
out, err = p.communicate()
idle = float(out.strip())
print(100-idle)
PSUtil、htop、mpstat 等所做的是从 /proc/stat
读取以 "cpu"
开头的行(实际上是第一行),然后根据其中的值计算百分比线。您可以在 man 5 proc
中找到该行值的含义(搜索 "proc/stat")。
这也是您提到的 grep cpu /proc/stat | awk ....
命令的作用。但是 /proc/stat
中的值表示自上次启动以来花费的时间!也许它们会在一段时间后环绕,我不确定,但关键是这些数字是在很长一段时间内测得的。
因此,如果您 运行 该命令,并且 运行 几秒钟(几分钟甚至几小时)后再次执行该命令,它们将不会发生太大变化!这就是为什么你总是看到它 return 5.12.
像top
这样的程序会记住以前的值并从新读取的值中减去它们。从结果中可以计算出实际反映最近 CPU 负载的 'live' 百分比。
尽可能简单地在 python 中做类似的事情,但没有 运行ning 外部命令来读取 /proc/stat
并为我们进行计算,我们可以存储值我们读入了一个文件。接下来 运行 我们可以读回它们,并从新值中减去它们。
#!/usr/bin/env python2.7
import os.path
# Read first line from /proc/stat. It should start with "cpu"
# and contains times spent in various modes by all CPU's totalled.
#
with open("/proc/stat") as procfile:
cpustats = procfile.readline().split()
# Sanity check
#
if cpustats[0] != 'cpu':
raise ValueError("First line of /proc/stat not recognised")
#
# Refer to "man 5 proc" (search for /proc/stat) for information
# about which field means what.
#
# Here we do calculation as simple as possible:
# CPU% = 100 * time_doing_things / (time_doing_things + time_doing_nothing)
#
user_time = int(cpustats[1]) # time spent in user space
nice_time = int(cpustats[2]) # 'nice' time spent in user space
system_time = int(cpustats[3]) # time spent in kernel space
idle_time = int(cpustats[4]) # time spent idly
iowait_time = int(cpustats[5]) # time spent waiting is also doing nothing
time_doing_things = user_time + nice_time + system_time
time_doing_nothing = idle_time + iowait_time
# The times read from /proc/stat are total times, i.e. *all* times spent
# doing things and doing nothing since last boot.
#
# So to calculate meaningful CPU % we need to know how much these values
# have *changed*. So we store them in a file which we read next time the
# script is run.
#
previous_values_file = "/tmp/prev.cpu"
prev_time_doing_things = 0
prev_time_doing_nothing = 0
try:
with open(previous_values_file) as prev_file:
prev1, prev2 = prev_file.readline().split()
prev_time_doing_things = int(prev1)
prev_time_doing_nothing = int(prev2)
except IOError: # To prevent error/exception if file does not exist. We don't care.
pass
# Write the new values to the file to use next run
#
with open(previous_values_file, 'w') as prev_file:
prev_file.write("{} {}\n".format(time_doing_things, time_doing_nothing))
# Calculate difference, i.e: how much the number have changed
#
diff_time_doing_things = time_doing_things - prev_time_doing_things
diff_time_doing_nothing = time_doing_nothing - prev_time_doing_nothing
# Calculate a percentage of change since last run:
#
cpu_percentage = 100.0 * diff_time_doing_things/ (diff_time_doing_things + diff_time_doing_nothing)
# Finally, output the result
#
print "CPU", cpu_percentage, "%"
这是一个与 top
不同的版本,每秒打印 CPU 次使用情况,在变量而不是文件中记住之前测量的 CPU 次:
#!/usr/bin/env python2.7
import os.path
import time
def get_cpu_times():
# Read first line from /proc/stat. It should start with "cpu"
# and contains times spend in various modes by all CPU's totalled.
#
with open("/proc/stat") as procfile:
cpustats = procfile.readline().split()
# Sanity check
#
if cpustats[0] != 'cpu':
raise ValueError("First line of /proc/stat not recognised")
# Refer to "man 5 proc" (search for /proc/stat) for information
# about which field means what.
#
# Here we do calculation as simple as possible:
#
# CPU% = 100 * time-doing-things / (time_doing_things + time_doing_nothing)
#
user_time = int(cpustats[1]) # time spent in user space
nice_time = int(cpustats[2]) # 'nice' time spent in user space
system_time = int(cpustats[3]) # time spent in kernel space
idle_time = int(cpustats[4]) # time spent idly
iowait_time = int(cpustats[5]) # time spent waiting is also doing nothing
time_doing_things = user_time + nice_time + system_time
time_doing_nothing = idle_time + iowait_time
return time_doing_things, time_doing_nothing
def cpu_percentage_loop():
prev_time_doing_things = 0
prev_time_doing_nothing = 0
while True: # loop forever printing CPU usage percentage
time_doing_things, time_doing_nothing = get_cpu_times()
diff_time_doing_things = time_doing_things - prev_time_doing_things
diff_time_doing_nothing = time_doing_nothing - prev_time_doing_nothing
cpu_percentage = 100.0 * diff_time_doing_things/ (diff_time_doing_things + diff_time_doing_nothing)
# remember current values to subtract next iteration of the loop
#
prev_time_doing_things = time_doing_things
prev_time_doing_nothing = time_doing_nothing
# Output latest perccentage
#
print "CPU", cpu_percentage, "%"
# Loop delay
#
time.sleep(1)
if __name__ == "__main__":
cpu_percentage_loop()
尝试在不使用 PSUtil
的情况下在 Python
中使用 CPU。
我尝试了以下方法,但似乎总是报告相同的数字...
def getCPUuse():
return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print }'").readline().strip(\
)))
print(getCPUuse())
这似乎总是报告 3.7%,即使我加载 CPU。
我也试过以下...
str(round(float(os.popen('''grep 'cpu ' /proc/stat | awk '{usage=(+)*100/(++)} END {print usage }' ''').readline()),2))
这似乎总是return 5.12。必须承认我真的不知道上面的内容。如果我在命令行中输入 grep cpu /proc/stat
我会得到类似这样的东西...
cpu 74429 1 19596 1704779 5567 0 284 0 0 0
cpu0 19596 0 4965 422508 1640 0 279 0 0 0
cpu1 18564 1 4793 427115 1420 0 1 0 0 0
cpu2 19020 0 4861 426916 1206 0 2 0 0 0
cpu3 17249 0 4977 428240 1301 0 2 0 0 0
我猜我的命令没有正确地从上面的输出中提取我所有 CPU 核心的值?
我的 objective 是在不使用 PSUtil 的情况下从我的设备 (Raspberry PI) 中获取总计 CPU %。该图应反映 OS 任务管理器中显示的内容。
这并不容易,因为您描述的大部分过程都提供 CPU 使用情况的累积或总平均值。
也许你可以尝试使用 systat
包自带的 mpstat
命令。
因此,我用于以下脚本的步骤是:
- 要求
mpstat
生成 2 份报告,一份立即生成,一份在 1 秒后生成 (mpstat 1 2
) - 然后我们得到
Average
行(最后一行) - 最后一列是
%idle
列,因此我们使用awk
中的 - 我们使用子进程中的
Popen
,但设置shell=True
以接受我们的管道 (|
) 选项。 - 我们执行命令(
communicate()
) - 使用
strip
清理输出
- 然后从 100 中减去(闲置百分比),这样我们就可以得到已使用的值。
$NF
变量得到它
因为它会休眠 1 second
,所以不用担心它不是 instant 命令。
import subprocess
cmd = "mpstat 1 2 | grep Average | awk '{print $NF}'"
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
out, err = p.communicate()
idle = float(out.strip())
print(100-idle)
PSUtil、htop、mpstat 等所做的是从 /proc/stat
读取以 "cpu"
开头的行(实际上是第一行),然后根据其中的值计算百分比线。您可以在 man 5 proc
中找到该行值的含义(搜索 "proc/stat")。
这也是您提到的 grep cpu /proc/stat | awk ....
命令的作用。但是 /proc/stat
中的值表示自上次启动以来花费的时间!也许它们会在一段时间后环绕,我不确定,但关键是这些数字是在很长一段时间内测得的。
因此,如果您 运行 该命令,并且 运行 几秒钟(几分钟甚至几小时)后再次执行该命令,它们将不会发生太大变化!这就是为什么你总是看到它 return 5.12.
像top
这样的程序会记住以前的值并从新读取的值中减去它们。从结果中可以计算出实际反映最近 CPU 负载的 'live' 百分比。
尽可能简单地在 python 中做类似的事情,但没有 运行ning 外部命令来读取 /proc/stat
并为我们进行计算,我们可以存储值我们读入了一个文件。接下来 运行 我们可以读回它们,并从新值中减去它们。
#!/usr/bin/env python2.7
import os.path
# Read first line from /proc/stat. It should start with "cpu"
# and contains times spent in various modes by all CPU's totalled.
#
with open("/proc/stat") as procfile:
cpustats = procfile.readline().split()
# Sanity check
#
if cpustats[0] != 'cpu':
raise ValueError("First line of /proc/stat not recognised")
#
# Refer to "man 5 proc" (search for /proc/stat) for information
# about which field means what.
#
# Here we do calculation as simple as possible:
# CPU% = 100 * time_doing_things / (time_doing_things + time_doing_nothing)
#
user_time = int(cpustats[1]) # time spent in user space
nice_time = int(cpustats[2]) # 'nice' time spent in user space
system_time = int(cpustats[3]) # time spent in kernel space
idle_time = int(cpustats[4]) # time spent idly
iowait_time = int(cpustats[5]) # time spent waiting is also doing nothing
time_doing_things = user_time + nice_time + system_time
time_doing_nothing = idle_time + iowait_time
# The times read from /proc/stat are total times, i.e. *all* times spent
# doing things and doing nothing since last boot.
#
# So to calculate meaningful CPU % we need to know how much these values
# have *changed*. So we store them in a file which we read next time the
# script is run.
#
previous_values_file = "/tmp/prev.cpu"
prev_time_doing_things = 0
prev_time_doing_nothing = 0
try:
with open(previous_values_file) as prev_file:
prev1, prev2 = prev_file.readline().split()
prev_time_doing_things = int(prev1)
prev_time_doing_nothing = int(prev2)
except IOError: # To prevent error/exception if file does not exist. We don't care.
pass
# Write the new values to the file to use next run
#
with open(previous_values_file, 'w') as prev_file:
prev_file.write("{} {}\n".format(time_doing_things, time_doing_nothing))
# Calculate difference, i.e: how much the number have changed
#
diff_time_doing_things = time_doing_things - prev_time_doing_things
diff_time_doing_nothing = time_doing_nothing - prev_time_doing_nothing
# Calculate a percentage of change since last run:
#
cpu_percentage = 100.0 * diff_time_doing_things/ (diff_time_doing_things + diff_time_doing_nothing)
# Finally, output the result
#
print "CPU", cpu_percentage, "%"
这是一个与 top
不同的版本,每秒打印 CPU 次使用情况,在变量而不是文件中记住之前测量的 CPU 次:
#!/usr/bin/env python2.7
import os.path
import time
def get_cpu_times():
# Read first line from /proc/stat. It should start with "cpu"
# and contains times spend in various modes by all CPU's totalled.
#
with open("/proc/stat") as procfile:
cpustats = procfile.readline().split()
# Sanity check
#
if cpustats[0] != 'cpu':
raise ValueError("First line of /proc/stat not recognised")
# Refer to "man 5 proc" (search for /proc/stat) for information
# about which field means what.
#
# Here we do calculation as simple as possible:
#
# CPU% = 100 * time-doing-things / (time_doing_things + time_doing_nothing)
#
user_time = int(cpustats[1]) # time spent in user space
nice_time = int(cpustats[2]) # 'nice' time spent in user space
system_time = int(cpustats[3]) # time spent in kernel space
idle_time = int(cpustats[4]) # time spent idly
iowait_time = int(cpustats[5]) # time spent waiting is also doing nothing
time_doing_things = user_time + nice_time + system_time
time_doing_nothing = idle_time + iowait_time
return time_doing_things, time_doing_nothing
def cpu_percentage_loop():
prev_time_doing_things = 0
prev_time_doing_nothing = 0
while True: # loop forever printing CPU usage percentage
time_doing_things, time_doing_nothing = get_cpu_times()
diff_time_doing_things = time_doing_things - prev_time_doing_things
diff_time_doing_nothing = time_doing_nothing - prev_time_doing_nothing
cpu_percentage = 100.0 * diff_time_doing_things/ (diff_time_doing_things + diff_time_doing_nothing)
# remember current values to subtract next iteration of the loop
#
prev_time_doing_things = time_doing_things
prev_time_doing_nothing = time_doing_nothing
# Output latest perccentage
#
print "CPU", cpu_percentage, "%"
# Loop delay
#
time.sleep(1)
if __name__ == "__main__":
cpu_percentage_loop()