Mat Mat - 7 months ago 48
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 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:


What is correct.

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.