Atharva Bhagwat

Stage 13: Running a script

0Plan
Stage 13Level up

Move from clicking cells to one command that rebuilds a result, so anyone can repeat it.

Notebooks are wonderful for exploring. Final results should not depend on cells you clicked in a certain order. A script is a plain .py file that runs from top to bottom with one command.

A first script

In VS Code, make a new file called make_figure.py in your project folder containing:

make_figure.py
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.read_csv("data/raw/pten-variant-abundance.csv")
miss = df[df["record_type"] == "missense"]

sns.histplot(data=miss, x="score", bins=40)
plt.xlabel("abundance score")
plt.ylabel("number of variants")
plt.savefig("results/figures/score_histogram.png", dpi=300, bbox_inches="tight")

print("saved results/figures/score_histogram.png")

Open a terminal in the project folder, activate your environment, and run it:

terminal
conda activate pybio
python make_figure.py

The file results/figures/score_histogram.png now exists, made entirely by code. Delete it and run the script again: it comes back.

A checklist for repeatable work

  1. Restart and run all every notebook. Fix anything that fails or depends on a cell you ran once and forgot.
  2. Move the final plotting code into a script like the one above.
  3. Save the environment: conda env export --from-history > environment.yml.
  4. Write the README: how to run it, and the choices you made.
  5. Delete results/ and run everything again to prove it rebuilds.

Where to go next

Exercises

These are also in the notebook. Try each one yourself before you open the solution.

Run your own script

Make a file called hello.py containing print("Hello from a script"), and run it from the terminal with python hello.py.
Show a solution (try it first)
one solution
echo 'print("Hello from a script")' > hello.py
python hello.py

Special thanks to Nilay!