How do you execute a Python script from inside a Bash shell script? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

How do you execute a Python script from inside a Bash shell script?

message-square
0

Invoke the target interpreter directly inside your Bash script—preferring the project virtual environment’s explicit binary ("$SCRIPT_DIR/.venv/bin/python" "$SCRIPT_DIR/process.py" "$@") or python3 path/to/script.py—combined with set -euo pipefail so the Bash script fails fast if Python exits with a non-zero status code, and quoting all variable expansions ("$@", "$INPUT_FILE") to prevent word-splitting on spaces. ### Basic Example ```bash #!/usr/bin/env bash set -euo pipefail # Resolve the directory containing this Bash script so relative paths never break SCRIPT_DIR=“$(cd “$(dirname “${BASH_SOURCE[0]}”)” && pwd)” PYTHON_BIN=“${SCRIPT_DIR}/.venv/bin/python” # Fallback to system python3 if no local .venv exists if [[ ! -x “$PYTHON_BIN” ]]; then PYTHON_BIN=“python3” fi # 1. Recommended: Execute external .py file and forward all CLI arguments ("$@") “$PYTHON_BIN” “${SCRIPT_DIR}/etl_job.py” --env prod “$@”

2. Capture Python stdout into a Bash variable:

ROW_COUNT=“$(”$PYTHON_BIN" “${SCRIPT_DIR}/count_rows.py” “data/users.csv”)" echo “Processed ${ROW_COUNT} rows.”

3. Run short inline multi-line Python via a quoted heredoc (<<'EOF'):

“$PYTHON_BIN” - <<‘EOF’ import sys print(f"Inline Python running on {sys.version.split()[0]}") EOF


### Key Details & Edge Cases

- **Always use `python3` or an explicit `.venv/bin/python` path (never bare `python`):**
  - On modern Debian/Ubuntu/macOS systems, bare `python` may not exist (`command not found`) or may point to a different global interpreter than your project dependencies. Invoking **`/path/to/.venv/bin/python`** works directly without needing `source .venv/bin/activate` inside the shell script.
- **Quote heredoc delimiters (`<<'EOF'` vs. `<<EOF`) when embedding inline Python:**
  - Unquoted `<<EOF` lets Bash expand `$var` and `` `cmd` `` *before* Python ever sees the code, corrupting Python strings or regexes containing `$`. Quoting **`<<'EOF'`** passes the Python source verbatim (pass values safely via environment variables like `TARGET_DIR="$dir" python3 - <<'EOF'` and read them in Python with `os.environ["TARGET_DIR"]`).
- **Passing CLI arguments when using inline heredoc (`python3 - arg1 arg2 <<'EOF'`):**
  - Using `-` as the script filename tells Python to read code from `stdin` while populating `sys.argv[1:]` with any trailing arguments (`"$@"`).
- **Avoid `UnboundLocalError` / buffering lag in non-interactive shells (`python3 -u`):**
  - When Bash pipes Python output (`python3 app.py | tee run.log`), Python buffers stdout in 4 KB–8 KB blocks instead of flushing line-by-line. Pass **`python3 -u`** (or export `PYTHONUNBUFFERED=1`) so progress logs appear in real time.
- **Check exit codes explicitly (`$?` or `if ! python3 ...; then`):** - `sys.exit(0)` signals success to Bash; any non-zero exit code (`sys.exit(1)` or an unhandled exception) signals failure. With `set -e`, Bash aborts immediately on a non-zero exit—if you want custom error handling instead, wrap the call in **`if ! "$PYTHON_BIN" job.py; then echo "Job failed" >&2; exit 1; fi`**.
- **Direct execution with a shebang (`chmod +x script.py`):**
  - Adding `#!/usr/bin/env python3` as line 1 of `script.py` and running `chmod +x script.py` lets Bash invoke `./script.py` directly like any compiled binary (note: ensure Unix `LF` line endings, as Windows `CRLF` causes `bad interpreter: No such file or directory`).

### Comparison of Ways to Run Python Inside a Bash Script

| Invocation Pattern | Dependency Isolation | Handles Multi-Line Python Cleanly? | Forwards CLI Args (`"$@"`)? | Best Used When |
| :--- | :--- | :--- | :--- | :--- |
| **`/path/to/.venv/bin/python script.py "$@"`** *(Recommended)* | **High** (uses exact virtualenv packages without `activate`) | **Yes** (separate `.py` file) | **Yes** | Production cron jobs, CI/CD pipelines, and multi-file Python projects. |
| **`python3 script.py "$@"`** \vert{} System / active `PATH` \vert{} **Yes** (separate `.py` file) \vert{} **Yes** \vert{} Portable scripts relying only on Python's standard library or system packages. \vert{} \vert{} **`python3 - "$@" <<'EOF' ... EOF`** | System / active `PATH` | **Yes** (no quote-escaping headaches) | **Yes** (`sys.argv[1:]`) | Self-contained Bash wrappers needing 5–30 lines of JSON/YAML/math processing without extra files. |
| **`python3 -c "import json; ..."`** | System / active `PATH` | **No** (awkward for indentation/quotes) | **Yes** (`python3 -c '...' "$1"`) \vert{} 1–2 line quick checks or expressions inside a shell pipeline. \vert{} \vert{} **`./script.py "$@"`** (with `#!/usr/bin/env python3`) | Active `PATH` (or hardcoded venv shebang) | **Yes** (separate `.py` file) | **Yes** | Treating a Python utility as a first-class executable CLI tool. |