Max Frai
Max Frai

Reputation: 64266

Python and regex

i have to parse need string. Here is command I execute in Linux console:

amixer get Master |grep Mono:

And get, for example,

Mono: Playback 61 [95%] [-3.00dB] [on]

Then i test it from python-console:

import re,os
print re.search( ur"(?<=\[)[0-9]{1,3}", u"  Mono: Playback 61 [95%] [-3.00dB] [on]" ).group()[0]

And get result: 95. It's that, what i need. But if I'll change my script to this:

print re.search( ur"(?<=\[)[0-9]{1,3}", str(os.system("amixer get Master |grep Mono:")) ).group()[0]

It'll returns None-object. Why?

Upvotes: 0

Views: 222

Answers (3)

John Millikin
John Millikin

Reputation: 200746

Instead of using os.system(), use the subprocess module:

from subprocess import Popen, PIPE
p = Popen("amixer get Master | grep Mono:", shell = True, stdout = PIPE)
stdout = p.stdout.read()
print re.search( ur"(?<=\[)[0-9]{1,3}", stdout).group()

Upvotes: 1

retracile
retracile

Reputation: 12339

os.system() returns the exit code from the application, not the text output of the application.

You should read up on the subprocess Python module; it will do what you need.

Upvotes: 7

Stefan Kendall
Stefan Kendall

Reputation: 67802

How to run a process and get the output:

http://docs.python.org/library/popen2.html

Upvotes: 0

Related Questions