P8 — Running Python Projects Locally
About 60 min
Before L6.13 — Package the Training Run, learn to operate a small local script. First use Project Workbench Step 0 for obtaining files, choosing a working environment, and installing dependencies; this guide does not repeat that setup. If you get every question below right, you can move to the next lesson. This optional guide, its diagnostic, and its Lab do not count toward course progress.
Quick Check
Goal
Execute Python from a documented repository root, distinguish interpreter/venv from packages, trace imports and relative paths, read/write JSON, run argparse scripts and interpret validator PASS/FAIL evidence.
Workbench first; terminal commands second
Follow Project Workbench — Step 0 to get the materials and create/activate an environment. The commands below assume that step has succeeded. python --version confirms the interpreter and python -m pip --version confirms which interpreter owns your pip. Use python -m pip install -r requirements.txt only when the specific project instructions require it. A virtual environment isolates packages; it does not make path problems disappear.
repository-root/
projects/
labs/
README.md
From the documented root, use pwd on macOS/Linux or Get-Location in Windows PowerShell to inspect your current directory. Commands such as python labs/notebooks/level-06/l06-13-package-run.py --help depend on the working directory and the repository layout. A relative file Path("outputs/metrics.json") uses the process's current working directory, not automatically the script folder.
Imports and module execution
import json
from pathlib import Path
from argparse import ArgumentParser
The first two are standard-library modules; from ... import ... imports a name. In a multi-file project, python -m package.module runs an importable module with the package context (from the appropriate root), while python path/to/script.py runs a file. If you get ModuleNotFoundError, check the active environment, repository root, spelling and documented invocation before editing sys.path.
JSON is text plus a data contract
import json
from pathlib import Path
record = {"run": "demo", "metrics": {"loss": 0.25}}
path = Path("run.json")
path.write_text(json.dumps(record, indent=2), encoding="utf-8")
loaded = json.loads(path.read_text(encoding="utf-8"))
assert loaded["metrics"]["loss"] == 0.25
Use json.dump(record, file)/json.load(file) when working with an open file handle; dumps/loads operate on strings. JSON supports objects, arrays, strings, numbers, booleans and null; it does not encode arbitrary PyTorch tensor objects automatically. Always avoid putting tokens, secrets or personal data in run artifacts.
argparse: options belong to a program
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--config", required=True)
args = parser.parse_args()
print(args.config)
A typical invocation is python train.py --config config.json. The shell supplies tokens; argparse parses them into args.config. Running with --help shows accepted flags and required options without starting model training. When tests call parse_args(["--config", "demo.json"]), they provide a synthetic command-line list.
Run the validator; interpret, don't guess
From the working directory given by L6.13, first inspect the applicable project/Lab instructions, then run their documented checker or python path/to/validator.py --help if it supports argparse. A PASS means the checks executed and their declared conditions passed; it does not prove the entire project is correct. A FAIL, assertion message, FileNotFoundError, or traceback tells you what to inspect next: read the final exception, then its source-line context and your current directory. Don't claim completion if commands were skipped.
For practice, the browser Lab below simulates --run demo --scores 2 4 6 as a list. Real shell setup and project-specific validator commands remain in Project Workbench and the actual Lab instructions.
Predict
Guided browser Lab
This offline browser Lab asks you to implement a tiny results dictionary, JSON serialization, and an argparse-to-function handoff. No system installation is needed for the Lab itself. Use the three staged hints and full answer if required; then copy the generated JSON to a local file only after completing Workbench Step 0.
Loading lab…
Optional first local run — PASS, expected FAIL, PASS
Complete Project Workbench Step 0, then open a terminal in the public materials repository root (where both projects/ and labs/ are visible). These commands use Python's standard library and the same real checker/fixture used in L6.13:
python labs/notebooks/level-06/l06-13-package-run.py --help
python labs/notebooks/level-06/l06-13-package-run.py projects/tests/l06/fixtures/passing
The second command should print PASS: packaged run p06-reference-reduced has required reproducibility evidence. Next, simulate removing a required field in memory (the fixture file is unchanged):
python labs/notebooks/level-06/l06-13-package-run.py projects/tests/l06/fixtures/passing --drop seed
Expect missing required field(s): seed and a nonzero exit. This is an intentional validation failure, not a broken Python setup. Run the original passing command one more time and confirm PASS. If the checker instead reports missing files, inspect your current directory before changing source code. On macOS/Linux use python3 if python is unavailable. Continue to the L6.13 Lab.
Quick Check
Key Takeaways
- Keep the documented environment and working directory explicit.
- json.load(s) reads; json.dump(s) writes or serializes, but only supported data types work by default.
- argparse errors and validator output are actionable evidence, not reasons to disable tests.