VorX
VorX

Reputation: 455

Script - Check CPU load (Python)

I've written for practicing purposes the following python script which checks the cpu load in case the processor reaches the 50% of the total usage.

import subprocess
import os

process1 = os.popen('cat /proc/cpuinfo | grep -c processor')
cmdread1 = process1.read()
process1.close()
num_of_procs = int(cmdread1)/2
print num_of_procs    # returns 1

process = os.popen('cat /proc/loadavg | awk \'{print $1}\'')
cmdread = process.read()
process.close()
cpu_usage = cmdread
print cpu_usage   # returns 0.15 or 0.xx (there is no load at the moment)
if cpu_usage>num_of_procs: # check if 0.15 is greater than 1 
   print "load!"
else:
   print "no load"

The script always returns "load" which is false. Moreover , I've check the boolean operations between a float and an integer and i see not something weird. Do you have any idea ? Thanks in advance.

Upvotes: 1

Views: 954

Answers (3)

phihag
phihag

Reputation: 287865

cpu_usage is a string, and num_of_procs an integer.

In Python 2, comparisons between strings and integers return an undefined value, cpython seems to always return True in your case.

You should cast cpu_usage to a number, like this:

cpu_usage = float(cmdread)

To avoid this class of errors, you can also use Python 3, where comparing types with no meaningful ordering between them raises an error:

>>> '0.001' < 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() < int()

Upvotes: 0

eli-bd
eli-bd

Reputation: 1634

cpu_usage is a string and num_of_procs is an Int.

So when you do:

if cpu_usage>num_of_procs:

it always returns false

Upvotes: 0

Srgrn
Srgrn

Reputation: 1825

it seems you forgot to cast cpu_usage. In the example below all required variables have been cast into float

import subprocess
import os

process1 = os.popen('cat /proc/cpuinfo | grep -c processor')
cmdread1 = process1.read()
process1.close()
num_of_procs = float(cmdread1)/2.0
print (num_of_procs)    # returns 1

process = os.popen('cat /proc/loadavg | awk \'{print $1}\'')
cmdread = process.read()
process.close()
cpu_usage = float(cmdread)
print (cpu_usage)   # returns 0.15 or 0.xx (there is no load at the moment)
if cpu_usage>num_of_procs: # check if 0.15 is greater than 1 
   print ("load!")
else:
   print ("no load")

Upvotes: 1

Related Questions