简体   繁体   中英

Get CPU % of given PID without psutil

I can't install any modules on some box, thus - I can't use psutil .

Need to get % of CPU usage by given PID.

One solution I see - use subprocess , but it looks horribly:

# 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).

To pass the variable to a string you can format it just like you did on line 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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