Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 9: Scripts, modules, and the command line

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.

1. Paths

The setup cell made this folder tree inside scratch:

trip/
├── plan.txt
├── notes/
│   └── day1.txt
└── photos/
    └── beach/
        └── sunset.txt

Run 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.

Exercise L9.1 (LO-9.1, ★, about 10 minutes)

Answer as relative paths, with / between folders (Windows accepts \ too, and the check accepts either).

  1. p1: your terminal is in trip/photos. What is the relative path of plan.txt?

  2. p2: your terminal is in trip/notes. What is the relative path of sunset.txt?

  3. p3: your terminal starts in trip. You type cd photos, then cd beach, then cd ../.., then cd notes. Give the folder you end in as a path relative to trip.

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.

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.

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".

  1. a1: python add.py 2 3

  2. a2: python add.py 2 three

  3. a3: python add.py 2

Run the next cell to see all three.

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.

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.

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.

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 F
  • The temperature is a positional argument named value, converted with type=float, so python convert.py hot stops with argparse’s own error and exit status 2.

  • A temperature below absolute zero, -273.15 C or -459.67 F, stops with parser.error and a message that contains below 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 running main.

Give each argument a help text, and try python convert.py -h with the cell after.

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.

Exercise L9.6 (LO-9.3, ★, about 10 minutes)

Predict the exit status of each command, as a whole number:

  1. e1: python greet.py Ada

  2. e2: python greet.py

  3. e3: python repeat.py hi --times 0

  4. e4: python stop1.py

  5. e5: python stop2.py

  6. e6: python stop3.py

Run the next cell to see each script’s output and exit status.

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.

  1. d1: the number of days from December 4, 2026, to March 1, 2027.

  2. d2: the date 100 days after December 4, 2026, as a date.

  3. d3: the name of the day of the week of January 1, 2027, such as "Monday".

  4. c1: the number of different ways to choose 6 numbers from 49, when order doesn’t matter. The math module has a function for it: search its page for “combinations”.

  5. m1: the median of [3, 1, 4, 1, 5, 9, 2, 6].

  6. Write count_sevens(seed, rolls). It seeds random with seed, rolls two six-sided dice rolls times, and returns how many rolls add up to 7.

Compute each value with code; don’t type the result.

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.

Exercise L9.8 (LO-9.5, ★★, about 20 minutes)

  1. has_matplotlib: this notebook runs in your course environment, where setup installed matplotlib. Will import matplotlib work in the new environment, env9? Answer True or False, then run the cell after the check to see.

  2. 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, run python -m pip list in your terminal, or run the cell under this one.

Run the next cell. It runs a line of Python with the new environment’s Python, then with this notebook’s.

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 .., as cd uses 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, and random; and

  • made 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.