How to execute a Program (or command) from a Python script?

You can execute a program or call a system command using the subprocess module in Python. The subprocess module provides functions and classes to interact with the system’s command-line interface.

Related: Python subprocess (Windows, Linux and MacOS examples)

Here’s how you can do it:

import subprocess

# Define the command you want to run as a list of strings
command = ["command_name", "arg1", "arg2"]

# Use subprocess.run() to execute the command
try:
    completed_process = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
    # The 'check=True' parameter will raise an exception if the command fails (non-zero exit code)

    # Get the output and error messages
    output = completed_process.stdout
    error = completed_process.stderr

    # Print the output and error messages
    print("Output:")
    print(output)

    print("Error:")
    print(error)

except subprocess.CalledProcessError as e:
    print(f"Command '{e.cmd}' failed with return code {e.returncode}.")
except Exception as e:
    print(f"An error occurred: {str(e)}")

Replace “command_name“, “arg1”, “arg2”, and so on with the actual command and its arguments that you want to execute. The subprocess.run() function will run the command, and you can capture the output and error messages if needed.

As shown in the example, make exceptions appropriately to handle cases where the command fails or errors occur during execution.

Note that the text=True argument captures the output as text (strings). If you need to work with binary data, you can omit it.

Here is a detailed article on subprocess with examples: subprocess (with Examples on Windows, Linux and MacOS)