How to Run Bash Scripts in Python

Aashish Sunuwar Feb 02, 2024
  1. Execute Bash Commands in Python 3
  2. Call a Bash Scripts From Within Python 3
  3. Pass Arguments to the Script
How to Run Bash Scripts in Python

Scripts written in Python are much easier to write than in Bash. In comparison to Bash scripts, managing Python scripts is simple.

Execute Bash Commands in Python 3

We can run Bash scripts within the Python scripts using the subprocess module and call the run function.

Example:

import subprocess


def main():
    subprocess.run(["echo", "Hello World"])


if __name__ == "__main__":
    main()

Output:

$python3 main.py
Hello World

Call a Bash Scripts From Within Python 3

We can specify the file path with run commands to run the existing bash scripts file.

Python:

subprocess.call("./script.sh")

Bash Script:

#!/bin/bash
echo "Hello World"

Output:

$python3 main.py
Hello World

Pass Arguments to the Script

We can also send certain arguments to the script by doing the following.

Python:

subprocess(["./script.sh", "argument"])

Bash:

#!/bin/bash
echo 'Stop this' $1

Output:

$python3 main.py
Stop this argument

Related Article - Python Subprocess