Driving a Python program from Bash
A launcher script that sets up and runs a Bézier curve fit — and how to make it work on any machine.
- Write a launcher script for a Python program
- Avoid hard-coded paths by locating the script's own directory
- Pass arguments and exit statuses through to the caller
The last script ties Bash to Python. It changes into the project folder, prints the Python version and runs a curve-fitting program, with tracing on:
#!/bin/bash
set -x
cd ${HOME}/programming-and-maths-Problems/bash_scripting_from_scratch
python --version
echo "We are inside code base and all set to visualize a bezier curve."
python ./curve_utils.py
curve_utils.py fits a Bézier curve to 16 points along a lane marking with a least-squares solve and plots the data, the control points and the curve. The mathematics — Bernstein polynomials, the Bernstein matrix and the pseudoinverse fit — is the subject of the Bézier lesson in the Python course, which animates this very fit.
Making the launcher portable
The script works on the machine it was written on. Two lines tie it there.
python. On current Ubuntu and Debian there is no python command by default, only python3. There the script prints python: command not found twice — it has no set -e, so it carries on past the first failure — and ends with status 127. Calling python3, or a project virtual environment’s interpreter, avoids the guess.
The hard-coded path. The cd assumes the repository sits in the home directory. A script can instead find its own folder:
#!/bin/bash
set -euo pipefail
cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
python3 --version
exec python3 ./curve_utils.py "$@"
${BASH_SOURCE[0]} is the path of the script itself, and readlink -f resolves it to an absolute path even through symlinks. "$@" forwards every argument the launcher received, each kept as one word. And exec replaces the shell with Python, so the caller sees Python’s exit status directly — a failed fit makes the launcher fail too, which is what scripts calling it need.
Try it yourself. Rewrite run_python_code.sh as above and run it from a different directory. Then give curve_utils.py an --order option with argparse (see the argparse lesson) and pass --order 5 through the launcher.