output of top on a linux box

Pradnyesh Sawant spradml at gmail.com
Mon Apr 9 13:26:04 EDT 2007


Hello,
I need the cpu usage of a linux box, for which i capture the output of
"top" using "popen". However, i am facing problems during string
handling. The code snippet is:-

top = os.popen("top -n 1")
rd = top.read().split("\n")
splt = rd[2].split()
# cpu = splt[2][:-4]  # why ain't this working ???
cpu = splt[2]
print "cpu usage: %s, %s" % (cpu, type(cpu))

the "print" statement prints, "cpu usage: 0.5%sy, <type 'str'>". i
tried my best to get rid of the "%sy" after the "0.5", but couldn't
succeed (even though the type of "cpu" is "string").

Also, one weird thing that was happening was that if i still "split"
the cpu string (removed the last 4 characters), the output of the next
print statement was wrong (specifically, the first 2 characters got
chipped off). This output is totally unexpected, and wrong...

Can anyone kindly help me in understanding what exactly is going on here.

Thanks a lot!



More information about the Python-list mailing list