Python exec bash command with examples

In Python, you can use the subprocess module to execute shell commands. This module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

Here’s an example of how you can execute a bash command using Python:

Example 1: Run a simple command

import subprocess

# Example 1: Run a simple command
result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
print("Output:", result.stdout)
print("Error:", result.stderr)
print("Return code:", result.returncode)

Example 2: Run a command with shell=True

import subprocess

# Example 2: Run a command with shell=True
result = subprocess.run("echo Hello, World!", shell=True, capture_output=True, text=True)
print("Output:", result.stdout)
print("Error:", result.stderr)
print("Return code:", result.returncode)

Example 3: Run a command and capture output in a variable

import subprocess

# Example 3: Run a command and capture output in a variable
command = "echo 'Python is awesome'"
output = subprocess.check_output(command, shell=True, text=True)
print("Output:", output)

Example 4: Run a command and handle exceptions

import subprocess

# Example 4: Run a command and handle exceptions
try:
    subprocess.run("nonexistent_command", check=True, shell=True)
except subprocess.CalledProcessError as e:
    print("Command failed with return code", e.returncode)
    print("Error output:", e.stderr)

In these examples:

Example 1 uses subprocess.run to execute the ls -l command and captures the output, error, and return code.

Example 2 uses subprocess.run with shell=True to execute a command as a string. This is useful when you need to use shell features like pipes or variables.

Example 3 uses subprocess.check_output to run a command and capture its output directly into a variable.

Example 4 demonstrates handling exceptions when a command fails. The check=True parameter raises a CalledProcessError if the command returns a non-zero exit code.

Be cautious when using commands with shell=True to prevent shell injection vulnerabilities. Always validate and sanitize user input if it’s included in the command.