简体   繁体   English

在没有psutil的情况下获取给定PID的CPU%

[英]Get CPU % of given PID without psutil

I can't install any modules on some box, thus - I can't use psutil . 我不能在某个盒子上安装任何模块,因此-我不能使用psutil

Need to get % of CPU usage by given PID. 需要通过给定的PID获得CPU使用率的百分比。

One solution I see - use subprocess , but it looks horribly: 我看到的一种解决方案-使用subprocess ,但看起来很可怕:

# CPU usage
cpu_percentage = subprocess.call("top -p 25393 -b -n 1 | grep -w java | awk '{print $9}'", shell=True, stdout=devnull)
print('\nCPU percentage usage by Java: %s%%' % cpu_percentage)

Also, such way - I can't find out how to pass variable, instead of PID directly (25393 in this exampel). 同样,这样-我无法找到如何传递变量,而不是直接传递PID (在本示例中为25393)。

To pass the variable to a string you can format it just like you did on line 3: 要将变量传递给字符串,可以像在第3行中一样设置其格式:

# CPU usage

# +Apply here:
cpu_percentage = subprocess.call("top -p %d -b -n 1 | grep -w java | awk '{print $9}'" % PID, shell=True, stdout=devnull)

# +like you did here:
print('\nCPU percentage usage by Java: %s%%' % cpu_percentage)

PID should be a int instance for make this work PID应该是一个int实例,以使其正常工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM