Mat Mat - 6 months ago 33
Bash Question

Call an external command in Python

How can I call an external command (as if I'd typed it at the Unix shell) from within a Python script?

I tried this code:

from subprocess import call
call(["ls", "-l"])


and it works.
But when I try this code in a Python script:

from subprocess import call
call(['sox', '/home/pi/OnoSW/data/opsoroassistant/rec.wav', '-n', 'stat', '2>&1', '|', 'sed', '-n', 's#^RMS amplitude:[^0-9]*\([0-9.]*\)$#\1#p'])


it doesn't works. I get this error:

sudo python getRMSAmplitude.py sox FAIL stat: Summary effect: unknown option


When I type this command in my Unix Shell:

sox ../../data/opsoroassistant/rec.wav -n stat 2>&1 | sed -n 's#^RMS amplitude:[^0-9]*\([0-9.]*\)$#\1#p'


I get:

0.001754


What is correct.

Answer
call([...], shell=True)

What's happening at the moment is that the rest of the arguments you're providing, '2>&1', '|', 'sed', '-n', 's#^RMS amplitude:[^0-9]*\([0-9.]*\)$#\1#p'] are being interpreted by sox as arguments, because there isn't a shell to interpret the output redirection or the pipe. Tell call to use a shell, and it will be interpreted the same way as your command line.

Comments