Best way to execute bash command with Python 2.x

Why this is not recommanded

Python is my favorite language for complex scripts and tooling. Unlike bash it's a real programming language and thus provide a better way to write maintainable scripts. I wouldn't advise anybody to run shell commands from Python script. The rigth way is respect the Python philosophy batteries included and use a Python library .

For example if you need to run a git subcommand, use Git Python.

Using a dedicated library allows:

  • better error management with exception
  • access to more features than those exposed via the CLI
  • better of support upgrade. If your command is updated, just update your dependency and your application will run without code changes

Below are good reasons to run bash commands from Python:

  • minimize dependencies of your application. This is especially true for big projects
  • there is no dedicated Python module and writing a Python binding is not profitable for one command

the solution

Beginners often look for a simple way to run command, capture the output in a variable and check the return code. They want an equivalent of the following bash statements:

my_output=$(mycmd arg1 arg2)
return_code=$?

Here is my favorite solution:

import tempfile
import subprocess

def execute_shell(cmd, *args):
    """
    @param name of the command, should be accessible from path
    @param list of the arguments
    Run the command and return a tuple (code, output)
    """
    parameters = [ cmd ]
    parameters.extend(args)

    # two oens are required otherwise the read get an error
    fd_tmp_out, tmp_output = tempfile.mkstemp()
    with open(tmp_output, "wb") as f:
        ret = subprocess.call(parameters, stdout=f, stderr=subprocess.STDOUT)
    with open(tmp_output, "r") as f:
        output = "".join(f.readlines())
    return ret, output.strip()
By @Romain JACQUET in
Tags :