在我的Raspberry pi 3上,我有一个Python脚本,该脚本在启动时在后台打开。在脚本中,有一个函数可以获取所用CPU的百分比。
功能如下:
`def getCPUuse():
return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()))`
如果我手动运行程序,则该函数会正确地将值返回给我,相反,如果程序是在后台启动时加载的,则函数不会向我返回任何值。
我到处搜索,但我不明白为什么。
有人可以帮我吗?
谢谢
PS,我不想使用psutil库!
我设法独自解决了。
我发布了解决方案,以便可以帮助他人!
def getCPUuse():
return(str(os.popen("top -b -n1 | grep 'Cpu(s)' | awk '{print $2 + $4}'").readline().strip()))