Objectives: LO-9.1, LO-9.2, LO-9.3, LO-9.4, LO-9.5
Prerequisites: Module 8, and the course environment
from Setting up your computer
Time: about 5.5 hours: 2 for this reading, 2 for Lab 9, and 1.5 for the
practice
So far you have run Python in notebook cells and run short scripts that a lab started for you. Real programs are run from a terminal, take instructions on the command line, live in several files, and use code that other people wrote. This module covers all four: the terminal itself, scripts that read arguments, programs split into modules, and the standard library and packages, installed into a virtual environment. Project 1, after Module 10, is a terminal program that uses all of them.
The terminal¶
A terminal is a window where you give the computer instructions by typing them. The program inside it that reads your commands is a shell: PowerShell on Windows, zsh on macOS, and usually bash on Linux. You used one in setup. This section explains what you typed there.
Open your py101 folder in VS Code and open a terminal with Terminal > New Terminal. The
terminal waits for a command after a prompt, which usually ends with the folder you are in. It
looks something like one of these, with your own names:
PS C:\Users\ada\Documents\py101>
ada@adas-mac py101 %
ada@laptop:~/Documents/py101$The first is PowerShell on Windows, the second zsh on macOS, and the third bash on Linux. Type a command after the prompt and press Enter. In the rest of this module, the commands leave out the prompt.
Where you are, and moving around¶
A terminal always works in one folder, its current folder (also called the working directory). Commands that name a file look for it there. These commands find out where you are and move you elsewhere. Windows PowerShell accepts the same short names as macOS and Linux for all of them:
| Command | What it does |
|---|---|
pwd | Print the current folder (“print working directory”) |
ls | List the files and folders in the current folder |
cd notes | Change into the folder notes, inside the current one |
cd .. | Change to the folder that contains the current one, its parent |
cd ~ | Change to your home folder |
mkdir m09 | Make a new folder named m09 in the current one |
Three habits save typing and mistakes:
Tab completion. Type the first letters of a file or folder name and press Tab; the shell finishes the name if only one matches.
History. Press the Up arrow to bring back the previous command, to run it again or edit it.
Stopping a program. Press Ctrl+C to stop a program that is running in the terminal, such as a loop that never ends.
Paths¶
A path names a file or folder by the folders that lead to it. An absolute path starts at
the top of the disk: C:\Users\ada\Documents\py101\notes.txt on Windows, or
/Users/ada/Documents/py101/notes.txt on macOS. A relative path starts at the current folder:
from py101, the same file is notes.txt. Two names are special in a relative path: . is the
current folder, and .. is its parent.
Windows separates folders with \, and macOS and Linux with /. PowerShell also accepts /, so
cd ../photos works in all three shells.
Worked example. Suppose your py101 folder holds this:
py101/
├── .venv/
├── lab08.ipynb
└── m09/
├── greet.py
└── data/
└── names.txtStart in py101. cd m09 moves into m09, where ls lists data and greet.py. From m09,
the relative path of names.txt is data/names.txt, and the relative path of the lab is
../lab08.ipynb: up one folder, then the file. cd data and then cd ../.. move down into
data and then up two folders, back to py101.
Running Python from the terminal¶
The course’s environment is the .venv folder in py101 (setup, step 6). Its own Python is
.venv\Scripts\python on Windows and .venv/bin/python on macOS and Linux. Those are relative
paths, so they work only from py101. From m09, one folder down, add .. in front:
Windows:
cd m09
..\.venv\Scripts\python greet.pymacOS and Linux:
cd m09
../.venv/bin/python greet.pyMany guides tell you to activate the environment first, after which python alone runs the
environment’s Python. On Windows, PowerShell’s default settings block the activation script, so
this course runs the environment’s Python by its path instead. Both ways run the same program.
Arguments: sys.argv¶
When you run a program, the words you type after its name are its command-line arguments.
Python puts them in a list, sys.argv, in the sys module. Save this as greet.py in m09:
import sys
print(sys.argv)
name = sys.argv[1]
print(f"Hello, {name}!")Then run it with an argument. (From here on, python stands for your environment’s Python, run
by its path as above.)
python greet.py Ada['greet.py', 'Ada']
Hello, Ada!sys.argv[0] is the script’s own name, and the arguments follow it, always as strings, even
42, which a program must convert with int as it would the result of input. The shell splits
the line at spaces, so python greet.py Ada Lovelace gives ['greet.py', 'Ada', 'Lovelace'], and
name is only 'Ada'. Quotes keep words together: python greet.py "Ada Lovelace" gives one
argument, 'Ada Lovelace'. With no argument at all, sys.argv[1] doesn’t exist:
['greet.py']
Traceback (most recent call last):
File "/home/you/py101/m09/greet.py", line 4, in <module>
name = sys.argv[1]
~~~~~~~~^^^
IndexError: list index out of rangeChecking len(sys.argv) by hand works for one argument, but it gets long fast. The argparse
module, later in this module, does the checking for you.
Modules¶
A module is a file of Python code that other code can use. Every .py file is a module, and
its name is the file’s name without .py. Splitting a program into modules keeps each file about
one thing, and lets several programs share the same functions.
Importing your own module¶
Save this as textstats.py in m09:
"""Functions that count things in text."""
PUNCTUATION = '.,;:!?"()-'
def words_in(text):
"""Return the words of text, in lowercase, without punctuation at their ends."""
words = []
for word in text.split():
word = word.strip(PUNCTUATION).lower()
if word != "":
words.append(word)
return words
def word_count(text):
"""Return how many words text has."""
return len(words_in(text))
print("Loading textstats; __name__ is", __name__)The string at the top is the module’s docstring, which says what the module is for, as a
function’s docstring does. The print at the bottom is there only to show when the module runs.
Now save this as report.py, in the same folder:
import textstats
text = "The cat sat. The dog didn't!"
print(textstats.word_count(text))
print(textstats.words_in(text))and run python report.py:
Loading textstats; __name__ is textstats
6
['the', 'cat', 'sat', 'the', 'dog', "didn't"]import textstats runs textstats.py once, from top to bottom, which defines its functions and
runs its print, and then gives report.py the name textstats for the module. You reach
anything the module defined with a dot: textstats.word_count. A second form copies chosen names
into your file, so you use them without the module’s name:
from textstats import word_count, words_inThe first form makes clear where each name comes from, which helps in a long program; the second
is shorter. You have already used both: import math and from collections import Counter.
Importing a module also makes Python save a translated copy of it, which loads faster, in a
folder named __pycache__ beside it. You never edit that folder, and Module 10 keeps it out of
your project’s history.
Where Python looks for modules¶
import textstats searches a list of folders in order, and takes the first textstats.py it
finds. The first folder is the one that holds the script you ran; then come the standard library
and the packages installed in your environment.
So a file of your own can hide a module from the standard library. If you save a script as
random.py, then import random in any script in the same folder imports your file, not the
standard library’s, and the error comes later:
AttributeError: module 'random' has no attribute 'randint'Python 3.13 and newer add a note to that line suggesting you rename your file. The fix is the
same: never name your own files after modules you use, such as random.py, math.py, or
statistics.py.
__name__ and the main guard¶
Every module has a variable __name__ (two underscores on each side). Python sets it to the
module’s name when the module is imported, which is why textstats.py printed textstats. When a
file is run as a script, Python sets its __name__ to "__main__" instead.
That difference lets one file work both as a script and as a module. Put the code that should run
only as a script in a function, by convention named main, and call it under a test of
__name__:
def main():
text = input("Text: ")
print(word_count(text), "words")
if __name__ == "__main__":
main()With these lines at the bottom of textstats.py (and its print removed), python textstats.py
asks for text and counts its words, while import textstats only defines the functions, so
report.py doesn’t stop to ask for text. This test is called the main guard. Give every
script one: it costs two lines, and later your tests (Module 13) can import the script’s
functions without running it.
Command-line programs with argparse¶
The standard library’s argparse module reads sys.argv for you: it converts each argument to
the type you ask for, gives defaults to the ones left out, writes a help message, and stops with
a clear error when the arguments are wrong. Save this as repeat.py:
"""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()The program describes its arguments, and parse_args returns an object with one attribute for
each:
"message"is a positional argument: the user must give it, and its place on the command line says which argument it is. It arrives asargs.message."--times"is an option, which the user may leave out.type=intconverts it, anddefault=1is its value when it’s missing. It arrives asargs.times. (A dash inside an option’s name becomes an underscore:--max-countarrives asargs.max_count.)"--shout"withaction="store_true"is a flag: an option that takes no value. It’sTruewhen the user types it andFalsewhen they don’t.
The loop variable _ is a name programmers use for a variable whose value they don’t need: here
only the number of passes matters.
python repeat.py hello --times 3
python repeat.py "good morning" --shouthello
hello
hello
GOOD MORNINGOptions can come before or after the positional argument. argparse also adds a -h option,
which prints a help message built from the descriptions you gave and stops:
python repeat.py -husage: repeat.py [-h] [--times TIMES] [--shout] message
Print a message several times.
positional arguments:
message the text to print
options:
-h, --help show this help message and exit
--times TIMES how many times to print it
--shout print it in capitalsOn Python 3.14 and newer, a terminal shows the help and the error messages in color.
Errors and the exit status¶
When the arguments are wrong, argparse prints a short usage line and an error that says what
was wrong, and stops the program:
$ python repeat.py hello --times x
usage: repeat.py [-h] [--times TIMES] [--shout] message
repeat.py: error: argument --times: invalid int value: 'x'
$ python repeat.py
usage: repeat.py [-h] [--times TIMES] [--shout] message
repeat.py: error: the following arguments are required: message
$ python repeat.py hi --times 0
usage: repeat.py [-h] [--times TIMES] [--shout] message
repeat.py: error: --times must be at least 1(Here a line that starts with $ is the command, typed after the prompt, and the lines after it
are what it printed.) The last error is the program’s own: parser.error reports a problem that
argparse can’t see, in the same form as its own errors.
Every program also ends with an exit status, a whole number it hands back to whatever started
it: 0 means it succeeded, and any other number means it failed. Tools that run other programs check
it: the automated checks you set up on GitHub in Module 13 stop at the first command that fails. The
argparse errors above end with status 2. An uncaught exception, such as the IndexError from
greet.py, ends with status 1. To see the status of the last command, type echo $? on macOS and
Linux, or $LASTEXITCODE in PowerShell.
To stop a program yourself with a message, use sys.exit:
if len(names) == 0:
sys.exit("error: no names given")sys.exit with a string prints it and ends the program with status 1; sys.exit(0) ends it
with status 0. Programs print error messages to a separate stream, standard error, so that
they still show in the terminal when the normal output goes somewhere else, such as into a file.
parser.error and sys.exit write there, and print(message, file=sys.stderr) does too.
The standard library¶
Python comes with hundreds of modules, its standard library, so many tasks need no extra installation. The library reference lists them by topic. To find one for a task, search that page for a word from the task, such as “date”, “random”, or “CSV”, then read the module’s page.
A module’s page starts with a summary, then documents each function. A function’s entry starts
with its signature, its name and parameters, such as random.randint(a, b), followed by what
it does and returns. Square brackets in a signature mark optional parameters, and a note such as
“Added in version 3.13” says which Python first has the function. In the interactive interpreter,
help(random.randint) prints the same entry.
Four modules come up again and again. random makes pseudo-random numbers: a fixed recipe
produces numbers that look random, starting from a number called the seed. Seeding with the
same number gives the same numbers again, which makes a run repeatable:
import random
random.seed(9)
print(random.randint(1, 6), random.randint(1, 6), random.randint(1, 6))
colors = ["red", "green", "blue", "gold"]
print(random.choice(colors))
random.shuffle(colors)
print(colors)
print(random.sample(range(1, 50), 6))4 5 3
blue
['gold', 'blue', 'red', 'green']
[22, 33, 30, 39, 6, 49]randint(a, b) includes both ends, unlike range. choice picks one item, shuffle reorders a
list in place, and sample picks several items without repeats. The module’s page warns that its
numbers mustn’t be used for security, such as passwords; the secrets module is for that.
math has the functions of school mathematics, datetime works with dates and times, and
statistics summarizes data:
import math
import statistics
from datetime import date, timedelta
print(math.sqrt(2), math.floor(-2.5), math.ceil(2.1))
start = date(2026, 12, 4)
print(start.strftime("%A"), date(2026, 12, 25) - start, start + timedelta(days=30))
scores = [72, 85, 85, 90, 64]
print(statistics.mean(scores), statistics.median(scores), round(statistics.stdev(scores), 2))1.4142135623730951 -3 3
Friday 21 days, 0:00:00 2027-01-03
79.2 85 10.8Subtracting two dates gives a timedelta, a length of time, and adding a timedelta to a date
gives another date, months and years included. strftime("%A") names the day of the week. stdev
is the sample standard deviation, a measure of how far values spread from their mean.
Virtual environments and packages¶
A package is a module, or a folder of modules, that someone has published for others to install.
The Python Package Index (PyPI) holds them, and pip, a tool that comes with
Python, installs them. JupyterLab, pytest, and matplotlib, which you installed in setup, are
packages.
Packages change, and two projects may need different versions of the same one. A virtual environment gives each project its own Python and its own packages, in a folder inside the project, so installing a package for one project can’t break another. You made one in setup:
Windows:
python -m venv .venvmacOS and Linux:
python3 -m venv .venv-m venv runs the standard library’s venv module, and .venv is the folder it makes.
python -m pip runs pip the same way, with whichever Python you start: the environment’s Python
installs into the environment. Install a package with its version pinned, that is, fixed
with ==:
.venv/bin/python -m pip install pytest==9.2.0On Windows, the path is .venv\Scripts\python, as before. Pinning means that the project gets
the same version every time it’s installed, on every computer, instead of whatever is newest that
day. A package can depend on others, which pip installs too: pytest 9.2.0 needs iniconfig,
packaging, pluggy, and pygments, and on Windows colorama.
python -m pip list shows every package in the environment, with its version, and
python -m pip freeze prints the same in the form name==version.
Recording a project’s dependencies¶
A project lists the packages it needs, its dependencies, in a text file named
requirements.txt, one per line:
pytest==9.2.0
matplotlib==3.11.2Anyone can then recreate the environment with one command, in a new environment:
.venv/bin/python -m pip install -r requirements.txtYou can list only the packages your code imports, as above, and let pip choose their
dependencies; or copy every line of pip freeze, which pins the dependencies too, so the
environment is the same everywhere. Many guides write the file with pip freeze > requirements.txt. In Windows PowerShell 5.1, > saves text as UTF-16, which Git treats as a
binary file, so copy the lines into the file in VS Code instead.
The .venv folder itself is never shared: it is large, it holds paths that work only on your
computer, and requirements.txt rebuilds it. Module 10 keeps it out of your project’s history.
Common misconceptions¶
| Belief | What happens | Example that breaks it |
|---|---|---|
sys.argv[1] is a number when the user types one | Every argument is a string | python add.py 2 3 with sys.argv[1] + sys.argv[2] prints 23 |
| A file can have any name | A file named after a module hides that module | random.py beside your script makes import random import it |
| Importing a module only defines its functions | It runs the whole file, once | report.py printed Loading textstats |
| A program that stops with its own error message has succeeded | argparse errors and sys.exit("…") end with a failure status | python repeat.py ends with status 2 |
pip install installs for every project | It installs into the environment whose Python runs it | A package installed into one .venv can’t be imported from another |
requirements.txt needs to list every package exactly | It can list only what you import directly | pytest==9.2.0 alone installs pytest’s dependencies too |
Summary¶
A terminal runs commands in a current folder.
pwd,ls,cd, andmkdirwork in PowerShell, zsh, and bash; a relative path starts at the current folder, and..is its parent.sys.argvholds the script’s name and then its arguments, all strings. Quotes keep words together.A
.pyfile is a module.importruns it once and gives access to its names; Python looks in the script’s folder first, so never name a file after a module you use. The main guard,if __name__ == "__main__":, runs code only when the file is a script.argparseconverts arguments, supplies defaults, writes-hhelp, and stops with a message and exit status 2 when the arguments are wrong. Exit status 0 means success;sys.exit("…")stops with a message and status 1.The library reference lists the standard library by topic; read a function’s signature and entry before using it. Seed
randomto make a run repeatable.A virtual environment holds one project’s packages. Install them with
python -m pip install name==version, and record them inrequirements.txt.
Self-check¶
Answer each question before you open its answer.
Your terminal is in
py101/m09. Which command runs the scriptpy101/tools/clean.pywith the environment’s Python, on your operating system?Answer
On Windows,
..\.venv\Scripts\python ..\tools\clean.py; on macOS and Linux,../.venv/bin/python ../tools/clean.py. Both paths go up topy101first. Runningcd ..and then.venv/bin/python tools/clean.pyworks too.What does
sys.argvhold forpython total.py 4 "5 6" --round?Answer
['total.py', '4', '5 6', '--round']. Every item is a string, and the quotes keep5 6together as one argument.shapes.pydefinesarea(width, height)and ends withprint(area(2, 3)). Another script runsfrom shapes import area. What happens, and how do you stop theprintfrom running on import?Answer
The import runs
shapes.py, so it prints6before the other script continues. Move theprintinto amainfunction and call it underif __name__ == "__main__":.Write the
argparselines for a script that takes a file name, an option--limitthat is a whole number with a default of 10, and a flag--verbose.Answer
parser = argparse.ArgumentParser(description="...") parser.add_argument("filename") parser.add_argument("--limit", type=int, default=10) parser.add_argument("--verbose", action="store_true") args = parser.parse_args()Help text for each argument, with
help="…", makes-huseful.Why does a project keep a
requirements.txtinstead of sharing its.venvfolder?Answer
.venvis large, holds paths that work only on the computer that made it, and contains programs built for that operating system.requirements.txtis a short text file from which anyone can build an equivalent environment withpip install -r requirements.txt.
Further reading¶
Software Carpentry, The Unix Shell, Navigating Files and Directories. A slower, hands-on lesson on the terminal, with exercises. Its commands are for bash, but the ideas apply in every shell.
The Python Tutorial, chapter 6, Modules, especially 6.1.1, Executing modules as scripts, and 6.1.2, The Module Search Path.
Argparse Tutorial, in the Python documentation. Positional arguments, options, and flags, one step at a time.
The Python Tutorial, chapter 12, Virtual Environments and Packages. Creating environments and managing packages with pip, in the language’s own words.
Al Sweigart, Automate the Boring Stuff with Python, 3rd edition, chapter 12, Designing and Deploying Command Line Programs. More about writing programs that people run from a terminal.
MIT, The Missing Semester of Your CS Education, Course Overview + Introduction to the Shell. For learners who want to go further with the shell than this course needs.