Stage 13: Running a script
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:
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:
conda activate pybio
python make_figure.pyThe 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
- Restart and run all every notebook. Fix anything that fails or depends on a cell you ran once and forgot.
- Move the final plotting code into a script like the one above.
- Save the environment:
conda env export --from-history > environment.yml. - Write the README: how to run it, and the choices you made.
- Delete
results/and run everything again to prove it rebuilds.
Where to go next
- 10 minutes to pandas: the official short tour. You can read all of it now.
- The seaborn gallery and matplotlib gallery: find a plot, copy the code, adapt it.
- Pick a question of your own about the PTEN table and answer it with a figure, a paragraph and a function.
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)
echo 'print("Hello from a script")' > hello.py
python hello.pySpecial thanks to Nilay!