Jobs Jobs - 5 months ago 27
Python Question

grep and then parse, python commandline

When I do, in python code,

os.system("mpstat 1 10 | grep Average")


I get, at stdout:

"Average: all 0.00 0.00 0.00 0.00" and a bunch of other things

What can I add to

mpstat 1 10 | grep Average | SOMETHING


to get a variable that contains the line that starts with Average?

I need the sum of the first number and the second number.

I tried the accepted answer here:

Can I redirect the stdout in python into some sort of string buffer?

But it doesn't work.

Answer

Do away with os.system call. Use subprocess.Popen instead. Here's how you'd do it:

>>> from subprocess import Popen
>>> from subprocess import PIPE
>>> mpstat = Popen(["mpstat", "1", "10"], stdout=PIPE)
>>> grep = Popen(["grep", "Average"], stdin=mpstat.stdout, stdout=PIPE)
>>> mpstat.stdout.close()
>>> res, err = grep.communicate()
>>> res
'Average:     all    0.79    0.00    0.46    0.03    0.00    0.01    0.00    0.00    0.00   98.71\n'
>>> res.strip().split()
['Average:', 'all', '0.79', '0.00', '0.46', '0.03', '0.00', '0.01', '0.00', '0.00', '0.00', '98.71']
>>> res.strip().split()[2:4]
['0.79', '0.00']
>>> values = map(float, res.strip().split()[2:4])
>>> values
[0.79, 0.0]