Objectives: LO-9.1, LO-9.2, LO-9.3, LO-9.4, LO-9.5
Prerequisites: the Module 9 reading and
Lab 8
Time: about 2 hours
In this lab you work out relative paths, read command-line arguments, turn a script into a
module with a main guard, build a temperature converter with argparse, predict exit statuses,
find and use functions from the standard library, and make a virtual environment and a
requirements file. As before, each exercise ends with a check cell that prints passed or says
what is wrong, and fails until you answer.
A notebook isn’t a terminal, so this lab runs scripts for you with a helper that passes them arguments, as the terminal would. The practice has you type the same commands in a real terminal.
Setup¶
Run the next cell first. It prints the version of Python, makes the scratch folder, sets the
random seed, imports importlib.metadata (section 7 uses it), and writes the files this lab
uses into scratch. It also defines the helpers from earlier labs, changed in two ways: they take
the script’s command-line arguments after its path, and run_script also shows the exit status.
run_script("scratch/greet.py", "Ada") runs what you would type in a terminal as
python greet.py Ada, from the scratch folder.
import importlib.metadata
import os
import random
import subprocess
import sys
from datetime import date, timedelta
print("Python", sys.version.split()[0])
os.makedirs("scratch", exist_ok=True)
random.seed(9)
TIME_LIMIT = 5 # seconds
STOPPED = f"(The script was still running after {TIME_LIMIT} seconds, so it was stopped.)\n"
# Runs a script with its arguments, showing each line of typed input after its prompt.
RUNNER = r"""
import builtins, os, sys, traceback
path = sys.argv[1]
sys.argv = sys.argv[1:]
sys.path[0] = os.path.dirname(os.path.abspath(path))
real_input = builtins.input
def input(prompt=""):
text = real_input(prompt)
print(text)
return text
builtins.input = input
source = open(path, encoding="utf-8").read()
try:
exec(compile(source, path, "exec"), {"__name__": "__main__", "__file__": path})
except SystemExit:
raise
except BaseException as error:
traceback.print_exception(type(error), error, error.__traceback__.tb_next)
sys.exit(1)
"""
def run_command(path, *arguments, typed=""):
"""Run a Python file with arguments and typed input; return its output and exit status."""
try:
result = subprocess.run(
[sys.executable, "-c", RUNNER, path, *arguments],
input=typed, capture_output=True, text=True, timeout=TIME_LIMIT,
)
except subprocess.TimeoutExpired:
return STOPPED, None
return result.stdout + result.stderr, result.returncode
def output_of(path, *arguments, typed=""):
"""Run a Python file with arguments, and return what it printed, errors included."""
return run_command(path, *arguments, typed=typed)[0]
def status_of(path, *arguments, typed=""):
"""Run a Python file with arguments, and return its exit status."""
return run_command(path, *arguments, typed=typed)[1]
def run_script(path, *arguments, typed=""):
"""Run a Python file as the terminal would, and show its output and exit status."""
output, status = run_command(path, *arguments, typed=typed)
print(output, end="")
print(f"(exit status {status})")
def write(path, text):
"""Write text to the file at path."""
with open(path, "w", encoding="utf-8") as file:
file.write(text)
for folder in ["scratch/trip/notes", "scratch/trip/photos/beach"]:
os.makedirs(folder, exist_ok=True)
write("scratch/trip/plan.txt", "Day 1: the coast. Day 2: the hills.\n")
write("scratch/trip/notes/day1.txt", "Windy, then sunny.\n")
write("scratch/trip/photos/beach/sunset.txt", "(a photo would be here)\n")
write("scratch/greet.py",
'import sys\n\nprint(sys.argv)\nname = sys.argv[1]\nprint(f"Hello, {name}!")\n')
write("scratch/add.py", "import sys\n\nprint(sys.argv[1] + sys.argv[2])\n")
print("Ready.")1. Paths¶
The setup cell made this folder tree inside scratch:
trip/
├── plan.txt
├── notes/
│ └── day1.txt
└── photos/
└── beach/
└── sunset.txtRun the next cell. os.walk goes through a folder and every folder inside it, and the cell
prints each folder and the files in it, so you can see that the tree is real.
for folder, subfolders, files in os.walk("scratch/trip"):
print(folder, files)Exercise L9.1 (LO-9.1, ★, about 10 minutes)¶
Answer as relative paths, with / between folders (Windows accepts \ too, and the check
accepts either).
p1: your terminal is intrip/photos. What is the relative path ofplan.txt?p2: your terminal is intrip/notes. What is the relative path ofsunset.txt?p3: your terminal starts intrip. You typecd photos, thencd beach, thencd ../.., thencd notes. Give the folder you end in as a path relative totrip.
Hint
.. goes up to the parent folder. To reach a file in another branch of the tree, go up until you reach a folder that contains both, then down.
p1 = "..."
p2 = "..."
p3 = "..."def reaches(start, relative, target):
"""Whether the relative path, from the folder start in scratch/trip, names target."""
path = os.path.join("scratch/trip", start, relative.replace("\\", "/"))
return os.path.normpath(path) == os.path.normpath(os.path.join("scratch/trip", target))
assert reaches("photos", p1, "plan.txt"), "p1: go up from photos to trip, where plan.txt is."
assert reaches("notes", p2, "photos/beach/sunset.txt"), (
"p2: go up from notes to trip, then down through photos and beach."
)
assert reaches(".", p3, "notes"), "p3: ../.. from trip/photos/beach is trip; then cd notes."
print("passed")2. Command-line arguments¶
Run the next cell. It runs greet.py from the reading with one argument, as
python greet.py Ada would, then with two words in one argument, as
python greet.py "Ada Lovelace" would. The quotes in a terminal do what the separate strings do
here: each string is one argument.
run_script("scratch/greet.py", "Ada")
run_script("scratch/greet.py", "Ada Lovelace")sys.argv[0] is scratch/greet.py here, because that is the path the script was run with.
Exercise L9.2 (LO-9.1, LO-9.3, ★, about 10 minutes)¶
The setup cell wrote scratch/add.py, which is meant to add two numbers:
import sys
print(sys.argv[1] + sys.argv[2])Without running it, predict what it prints for each command. For a command that stops with an
error, give only the kind of error, such as "TypeError".
a1:python add.py 2 3a2:python add.py 2 threea3:python add.py 2
a1 = "..."
a2 = "..."
a3 = "..."assert a1 == "23", "a1: every argument is a string, and + joins two strings."
assert a2 == "2three", "a2: the same: two strings, joined."
assert a3 == "IndexError", "a3: with one argument, sys.argv has no item at index 2."
print("passed")Run the next cell to see all three.
run_script("scratch/add.py", "2", "3")
run_script("scratch/add.py", "2", "three")
run_script("scratch/add.py", "2")Exercise L9.3 (LO-9.3, ★★, about 15 minutes)¶
Rewrite add.py in the next cell so that it prints the sum of all its arguments, as
numbers that may have decimals: python add.py 2 3 4.5 prints 9.5, python add.py 7 prints
7.0, and python add.py with no arguments prints 0.0. Running the cell saves the file; the
cell after it runs your script.
Hint
The arguments are sys.argv[1:]. Start a total at 0.0, and add float(...) of each.
%%writefile scratch/add.py
import sys
print(sys.argv[1] + sys.argv[2])run_script("scratch/add.py", "2", "3", "4.5")assert output_of("scratch/add.py", "2", "3", "4.5") == "9.5\n", "2 3 4.5 should print 9.5"
assert output_of("scratch/add.py", "7") == "7.0\n", "a single 7 should print 7.0"
assert output_of("scratch/add.py") == "0.0\n", "no arguments should print 0.0"
assert output_of("scratch/add.py", "-1", "1") == "0.0\n", "-1 and 1 should print 0.0"
print("passed")3. Modules and the main guard¶
The next cell writes two files: shapes.py, a module of area functions that ends by showing
them off, and use_shapes.py, a script that imports it. Run it, then the cell after, which runs
use_shapes.py.
SHAPES = '''"""Areas of simple shapes."""
import math
def rectangle_area(width, height):
"""Return the area of a width-by-height rectangle."""
return width * height
def circle_area(radius):
"""Return the area of a circle of the given radius."""
return math.pi * radius ** 2
print("A 3 by 4 rectangle:", rectangle_area(3, 4))
print(f"A circle of radius 1: {circle_area(1):.2f}")
'''
write("scratch/shapes.py", SHAPES)
write("scratch/use_shapes.py", "import shapes\n\nprint(shapes.rectangle_area(2, 6))\n")
print(SHAPES)run_script("scratch/use_shapes.py")use_shapes.py printed three lines, not one: importing shapes ran the whole file, its two
print lines included.
Exercise L9.4 (LO-9.2, ★★, about 15 minutes)¶
Rewrite shapes.py in the next cell so that its two print lines run when you run
python shapes.py, but not when another script imports it. Put them in a function named
main, and call it under a main guard. Keep both area functions as they are.
%%writefile scratch/shapes.py
"""Areas of simple shapes."""
import math
def rectangle_area(width, height):
"""Return the area of a width-by-height rectangle."""
return width * height
def circle_area(radius):
"""Return the area of a circle of the given radius."""
return math.pi * radius ** 2
print("A 3 by 4 rectangle:", rectangle_area(3, 4))
print(f"A circle of radius 1: {circle_area(1):.2f}")run_script("scratch/shapes.py")
run_script("scratch/use_shapes.py")assert output_of("scratch/use_shapes.py") == "12\n", (
"use_shapes.py should print only 12: importing shapes must not run the two print lines."
)
shapes_output = "A 3 by 4 rectangle: 12\nA circle of radius 1: 3.14\n"
assert output_of("scratch/shapes.py") == shapes_output, (
"Running shapes.py as a script should still print its two lines."
)
assert "def main" in open("scratch/shapes.py", encoding="utf-8").read(), "Name the function main."
print("passed")4. A command-line program with argparse¶
Exercise L9.5 (LO-9.2, LO-9.3, ★★★, about 25 minutes)¶
Finish convert.py, a temperature converter, in the next cell. It converts Celsius to
Fahrenheit, or Fahrenheit to Celsius with the flag --to-celsius, and prints both temperatures
with one decimal:
$ python convert.py 100
100.0 C = 212.0 F
$ python convert.py 212 --to-celsius
212.0 F = 100.0 C
$ python convert.py -40
-40.0 C = -40.0 FThe temperature is a positional argument named
value, converted withtype=float, sopython convert.py hotstops withargparse’s own error and exit status 2.A temperature below absolute zero, -273.15 C or -459.67 F, stops with
parser.errorand a message that containsbelow absolute zero, such as-500.0 C is below absolute zero.The functions and the constants are written for you. Write
main, and keep the main guard, so that another script can import the two functions without runningmain.
Give each argument a help text, and try python convert.py -h with the cell after.
%%writefile scratch/convert.py
"""Convert temperatures between Celsius and Fahrenheit."""
import argparse
ABSOLUTE_ZERO_C = -273.15
ABSOLUTE_ZERO_F = -459.67
def c_to_f(celsius):
"""Return the Fahrenheit temperature equal to celsius."""
return celsius * 9 / 5 + 32
def f_to_c(fahrenheit):
"""Return the Celsius temperature equal to fahrenheit."""
return (fahrenheit - 32) * 5 / 9
def main():
print("main isn't written yet")
if __name__ == "__main__":
main()run_script("scratch/convert.py", "100")
run_script("scratch/convert.py", "-h")
run_script("scratch/convert.py", "hot")write("scratch/use_convert.py", "import convert\n\n"
"print(round(convert.c_to_f(37), 1))\nprint(round(convert.f_to_c(98.6), 1))\n")
assert output_of("scratch/use_convert.py") == "98.6\n37.0\n", (
"Importing convert must not run main: keep the main guard."
)
assert output_of("scratch/convert.py", "100") == "100.0 C = 212.0 F\n"
assert output_of("scratch/convert.py", "212", "--to-celsius") == "212.0 F = 100.0 C\n"
assert output_of("scratch/convert.py", "--to-celsius", "32") == "32.0 F = 0.0 C\n", (
"The flag may come before the value."
)
assert output_of("scratch/convert.py", "-40") == "-40.0 C = -40.0 F\n"
assert output_of("scratch/convert.py", "37.5") == "37.5 C = 99.5 F\n"
output, status = run_command("scratch/convert.py", "hot")
assert status == 2 and "invalid float value" in output, "Use type=float for value."
output, status = run_command("scratch/convert.py", "-500")
assert status == 2 and "below absolute zero" in output, (
"-500 C is below absolute zero: report it with parser.error."
)
output, status = run_command("scratch/convert.py", "-460", "--to-celsius")
assert status == 2 and "below absolute zero" in output, "-460 F is below absolute zero too."
assert status_of("scratch/convert.py", "-459", "--to-celsius") == 0, (
"-459 F is above absolute zero (-459.67 F), so it converts."
)
print("passed")5. Exit statuses¶
The next cell writes three more short scripts, stop1.py, stop2.py, and stop3.py, and the
reading’s repeat.py. It prints the three short ones.
write("scratch/stop1.py", 'import sys\n\nsys.exit("error: no input file given")\n')
write("scratch/stop2.py", 'import sys\n\nprint("All done.")\nsys.exit()\n')
write("scratch/stop3.py", 'import sys\n\nprint("Three problems found.")\nsys.exit(3)\n')
REPEAT = '''"""Print a message several times."""
import argparse
def main():
parser = argparse.ArgumentParser(description="Print a message several times.")
parser.add_argument("message", help="the text to print")
parser.add_argument("--times", type=int, default=1, help="how many times to print it")
parser.add_argument("--shout", action="store_true", help="print it in capitals")
args = parser.parse_args()
if args.times < 1:
parser.error("--times must be at least 1")
text = args.message
if args.shout:
text = text.upper()
for _ in range(args.times):
print(text)
if __name__ == "__main__":
main()
'''
write("scratch/repeat.py", REPEAT)
for name in ["stop1.py", "stop2.py", "stop3.py"]:
print(f"--- {name}")
print(open(f"scratch/{name}", encoding="utf-8").read())Exercise L9.6 (LO-9.3, ★, about 10 minutes)¶
Predict the exit status of each command, as a whole number:
e1:python greet.py Adae2:python greet.pye3:python repeat.py hi --times 0e4:python stop1.pye5:python stop2.pye6:python stop3.py
e1 = None
e2 = None
e3 = None
e4 = None
e5 = None
e6 = Nonepredicted = {"e1": e1, "e2": e2, "e3": e3, "e4": e4, "e5": e5, "e6": e6}
actual = {
"e1": status_of("scratch/greet.py", "Ada"),
"e2": status_of("scratch/greet.py"),
"e3": status_of("scratch/repeat.py", "hi", "--times", "0"),
"e4": status_of("scratch/stop1.py"),
"e5": status_of("scratch/stop2.py"),
"e6": status_of("scratch/stop3.py"),
}
wrong = [name for name in predicted if predicted[name] != actual[name]]
assert not wrong, "These predictions are wrong: " + ", ".join(wrong)
print("passed")Run the next cell to see each script’s output and exit status.
run_script("scratch/greet.py")
run_script("scratch/repeat.py", "hi", "--times", "0")
run_script("scratch/stop1.py")
run_script("scratch/stop3.py")6. The standard library¶
Exercise L9.7 (LO-9.4, ★★, about 20 minutes)¶
Use the standard library for each answer, and find any function you don’t know in the
library reference. The setup cell already
imported date and timedelta from datetime; import anything else you need in the answer
cell.
d1: the number of days from December 4, 2026, to March 1, 2027.d2: the date 100 days after December 4, 2026, as adate.d3: the name of the day of the week of January 1, 2027, such as"Monday".c1: the number of different ways to choose 6 numbers from 49, when order doesn’t matter. Themathmodule has a function for it: search its page for “combinations”.m1: the median of[3, 1, 4, 1, 5, 9, 2, 6].Write
count_sevens(seed, rolls). It seedsrandomwithseed, rolls two six-sided dicerollstimes, and returns how many rolls add up to 7.
Compute each value with code; don’t type the result.
d1 = None
d2 = None
d3 = None
c1 = None
m1 = None
def count_sevens(seed, rolls):
"""Seed random with seed, roll two dice rolls times, and return how many totals are 7."""
return Noneassert d1 == 87, "d1: subtract the two dates, and take .days"
assert d2 == date(2027, 3, 14), "d2: add timedelta(days=100) to the date"
assert d3 == "Friday", "d3: strftime(\"%A\") names the day"
assert c1 == 13_983_816, "c1: math.comb(n, k) counts the ways to choose k of n"
assert m1 == 3.5, "m1: statistics.median; with an even count, the mean of the middle two"
first = count_sevens(9, 1000)
assert type(first) == int, "count_sevens should return a whole number"
assert count_sevens(9, 1000) == first, "The same seed must give the same count."
assert 880 <= count_sevens(1, 6000) <= 1120, (
"About one roll in six adds up to 7, so 6,000 rolls should give about 1,000."
)
print("passed")A seed makes a run repeatable, which is how you test a program that uses random numbers, and
why Project 1 asks for a --seed option.
7. Virtual environments¶
The next cell makes a new virtual environment in scratch/env9. It passes --without-pip,
which leaves pip out: this environment is only for looking at, and leaving pip out makes it in
about a tenth of a second. (--clear empties the folder first, if the cell ran before.) In your
own projects, leave both out, as setup did. The cell then works out the path of the new
environment’s Python, which is in Scripts on Windows and in bin elsewhere.
subprocess.run([sys.executable, "-m", "venv", "--without-pip", "--clear", "scratch/env9"],
check=True)
if os.name == "nt":
env_python = os.path.join("scratch", "env9", "Scripts", "python")
else:
env_python = os.path.join("scratch", "env9", "bin", "python")
print("This notebook's environment:", sys.prefix)
print("The new environment's Python:", env_python)Exercise L9.8 (LO-9.5, ★★, about 20 minutes)¶
has_matplotlib: this notebook runs in your course environment, where setup installed matplotlib. Willimport matplotlibwork in the new environment,env9? AnswerTrueorFalse, then run the cell after the check to see.Write a requirements file,
scratch/requirements.txt, for a project that imports matplotlib and pytest, pinned to the versions installed in your course environment, one per line. To find the versions, runpython -m pip listin your terminal, or run the cell under this one.
for package in ["matplotlib", "pytest"]:
print(package, importlib.metadata.version(package))has_matplotlib = None%%writefile scratch/requirements.txt
# Write the requirements here, in place of this line.assert has_matplotlib is False, (
"has_matplotlib: each environment has its own packages, and env9 is new and empty."
)
lines = [line.strip() for line in open("scratch/requirements.txt", encoding="utf-8")
if line.strip() and not line.startswith("#")]
pins = {}
for line in lines:
assert "==" in line, f"Pin each package with ==, as in name==version: {line!r}"
name, version = line.split("==")
pins[name.strip().lower()] = version.strip()
assert sorted(pins) == ["matplotlib", "pytest"], "List exactly matplotlib and pytest."
for name, version in pins.items():
assert version == importlib.metadata.version(name), (
f"{name} is {importlib.metadata.version(name)} in your course environment, not {version}"
)
print("passed")Run the next cell. It runs a line of Python with the new environment’s Python, then with this notebook’s.
check = "import sys; print(sys.prefix); import matplotlib; print(matplotlib.__version__)"
for python in [env_python, sys.executable]:
result = subprocess.run([python, "-c", check], capture_output=True, text=True)
print(result.stdout + result.stderr.strip().split("\n")[-1])The new environment’s Python can’t import matplotlib, because no one installed it there. That is
the point of environments: each project gets exactly the packages its requirements.txt lists,
and python -m pip install -r requirements.txt would install them into env9.
Summary¶
In this lab you:
worked out relative paths with
.., ascduses them;read command-line arguments from
sys.argv, and converted them from strings;added a main guard, so a script’s functions can be imported without running it;
built a converter with
argparse, with a positional argument, a flag, and its own error;predicted the exit statuses of scripts that succeed, crash, and stop with
sys.exit;found and used functions in
datetime,math,statistics, andrandom; andmade a virtual environment, saw that its packages are its own, and wrote a requirements file.
Next, the Module 9 practice has you do the same in a real terminal.