Executing command line programs from within python

PythonCommand Line

Python Problem Overview


I'm building a web application that will is going to manipulate (pad, mix, merge etc) sound files and I've found that sox does exactly what I want. Sox is a linux command line program and I'm feeling a little uncomfortable with having the python web app starting new sox processes on my server on a per request basis.

Example:

import os
os.system('sox input.wav -b 24 output.aiff rate -v -L -b 90 48k')

This whole setup seems a little unstable to me.

So my question is, what's the best practice for running command line programs from within a python (or any scripting language) web app?

Message queues would be one thing to implement in order to get around the whole request response cycle. But is there other ways to make these things more elegant?

Python Solutions


Solution 1 - Python

The subprocess module is the preferred way of running other programs from Python -- much more flexible and nicer to use than os.system.

import subprocess
#subprocess.check_output(['ls', '-l'])  # All that is technically needed...
print(subprocess.check_output(['ls', '-l']))

Solution 2 - Python

> This whole setup seems a little unstable to me.

Talk to the ffmpegx folks about having a GUI front-end over a command-line backend. It doesn't seem to bother them.

Indeed, I submit that a GUI (or web) front-end over a command-line backend is actually more stable, since you have a very, very clean interface between GUI and command. The command can evolve at a different pace from the web, as long as the command-line options are compatible, you have no possibility of breakage.

Solution 3 - Python

If you're concerned about server performance then look at capping the number of running sox processes. If the cap has been hit you can always cache the request and inform the user when it's finished in whichever way suits your application.

Alternatively, have the n worker scripts on other machines that pull requests from the db and call sox, and then push the resulting output file to where it needs to be.

Solution 4 - Python

I am not familiar with sox, but instead of making repeated calls to the program as a command line, is it possible to set it up as a service and connect to it for requests? You can take a look at the connection interface such as sqlite for inspiration.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMattiasView Question on Stackoverflow
Solution 1 - PythondF.View Answer on Stackoverflow
Solution 2 - PythonS.LottView Answer on Stackoverflow
Solution 3 - PythonDale ReidyView Answer on Stackoverflow
Solution 4 - Pythonz -View Answer on Stackoverflow