Python 3.10
Let’s say I have a python script like this:
import psutil
print("="*40, "CPU Info", "="*40)
print("Physical cores:", psutil.cpu_count(logical=False))
print("Total cores:", psutil.cpu_count(logical=True))
print("CPU Usage Per Core:")
for i, percentage in enumerate(psutil.cpu_percent(percpu=True, interval=1)):
print(f"Core {i}: {percentage}%")
print(f"Total CPU Usage: {psutil.cpu_percent()}%")
Which gives the following output:
======================================== CPU Info ========================================
Physical cores: 4
Total cores: 8
CPU Usage Per Core:
Core 0: 13.6%
Core 1: 1.5%
Core 2: 18.5%
Core 3: 0.0%
Core 4: 16.9%
Core 5: 7.7%
Core 6: 9.2%
Core 7: 9.2%
Total CPU Usage: 9.7%
What I need to be able to add to this is, if any of cores 0 through 3 are above 50% usage, then do something (I know how to write the do something part of the code).
How would I write the if part of this? Where I’m stuck is indicating the core numbers explicitly.
I will also be required to do this with other cores, and sometimes all of them, but if I see the syntax for my above example, I should be able to figure out how to cover other examples.
>Solution :
inside the for loop you should write
if percentage > 50 and i < 4:
#DO