11 Python programs
This chapter shifts from interactive use of Python to building runnable programs and command-line scripts. It explains why command-line techniques matter even in GUI-centric environments, especially for automating tasks and processing many files, and it shows how to work within notebook environments like Colaboratory while preparing code that also runs well on desktops. Throughout, the chapter emphasizes simple, composable tools, practical execution across operating systems, and habits that scale from tiny scripts to reusable modules and applications.
Core practices include organizing code around a controlling main function and protecting execution with the if __name__ == "__main__" guard so modules can be imported safely. The chapter covers command-line arguments first via sys.argv and then with argparse for robust parsing, types, defaults, and usage messages. It demonstrates reading from standard input and writing to standard output for redirection and pipelines, and shows how fileinput streamlines processing multiple files. Execution details are addressed for Linux/UNIX (shebang lines and chmod), macOS (Terminal and Python Launcher), Windows (Command Prompt/PowerShell, PATH and PATHEXT, and the option of WSL), and Colaboratory (using a shell prefix to run host commands), noting small platform differences around redirection.
Moving beyond one-file scripts, the chapter illustrates separating reusable logic from the command-line interface, adding test modes for quick regression checks, and structuring modules so functions can be imported elsewhere. It then surveys distribution options: wheels for packaging and dependency management; executable zip archives via zipapp or pex; and platform-focused tools such as py2exe, py2app, and freeze, with trade-offs in size, complexity, and portability. A lab exercise caps the chapter by refactoring a file-statistics program to emulate the wc utility and its -l, -w, -c, and -L options, highlighting careful argparse setup, output formatting, and the importance of precise requirements—useful both for human refactoring and when guiding AI-generated solutions.
Summary
- Python scripts and modules in their most basic form are just sequences of Python statements placed in a file.
- Modules can be instrumented to run as scripts, and scripts can be set up so that they can be imported as modules.
- Scripts can be made executable on the UNIX, macOS, or Windows command lines. They can be set up to support command-line redirection of their input and output, and with the argparse module, it’s easy to parse out complex combinations of command-line arguments.
- On macOS, you can use the Python Launcher to run Python programs, either individually or as the default application for opening Python files.
- On Windows, you can call scripts in several ways: by opening them with a double-click, using the Run window, or using a command-prompt window.
- Python scripts can be distributed as scripts, as bytecode, or in special packages called wheels.
- py2exe, py2app, and the freeze tool provide an executable Python program that runs on machines that don’t contain a Python interpreter.
- Now that you have an idea of the ways to create scripts and applications, the next step is looking at how Python can interact with and manipulate filesystems.
FAQ
What is the simplest, recommended structure of a Python script?
Define a controlling function (often named main) and call it under a __name__ guard so the file can be run as a script or imported without side effects:def main():
print("Hello from a script")
if __name__ == "__main__":
main()
This pattern scales better as scripts grow and allows reuse via imports.
How do I run a Python script from Colaboratory, Linux/macOS, or Windows?
- Colaboratory: prefix shell commands with !, e.g.! python script.py (ensure the file exists in the session).- Linux/macOS: in a terminal, ensure Python is on PATH and run
python script.py (or python3 on some systems).- Windows: use Terminal/Command Prompt/PowerShell, cd to the folder, then
python script.py. If python isn’t found, add it to PATH or install via Microsoft Store.
How do command-line arguments work in Python?
They are available as a list of strings insys.argv (import sys). The first element is the script name. All values are strings, so convert types as needed (e.g., int(sys.argv[1])).
What does if __name__ == "__main__": do, and why should I use it?
It ensures certain code runs only when the file is executed as a script, not when imported as a module. Place script-only code (like calling main) under:if __name__ == "__main__":
main()
This lets the same file serve as both a reusable module and a runnable script.
How can I redirect input/output and chain scripts on the command line?
- Usesys.stdin to read and sys.stdout (or print) to write in your script.- Shell redirection:
script < infile > outfile (append with >>).- Piping:
scriptA ... | scriptB ... sends A’s output to B’s input.Example: a filter script that reads stdin, transforms text, and writes to stdout can be composed with other commands.
When should I use argparse, and how?
Useargparse to parse positional and optional arguments and auto-generate help/usage. Basic flow:
- Create a parser: parser = ArgumentParser().- Add arguments:
add_argument("infile"), add_argument("-q", "--quiet", action="store_false", dest="verbose", default=True).- Parse:
args = parser.parse_args().It validates required args, converts types, and reports errors with a usage message.
What is the fileinput module and when is it useful?
fileinput lets you iterate over lines from multiple files (taken from command-line arguments) or stdin with a simple loop:
import fileinput
for line in fileinput.input():
...
Helpers include fileinput.filename(), isfirstline(), lineno(), and nextfile(). It’s convenient for scripts that process many files or act as filters.
How do I make a script directly executable on UNIX-like systems?
- Add a shebang on the first line:#!/usr/bin/env python3.- Make it executable:
chmod +x script.py.- Put it on your PATH (e.g., in
~/bin) and run it by name. Redirection (<, >) and pipes work in UNIX shells.
How do I combine scripts and modules effectively?
- Put reusable logic in functions and keep “script plumbing” in amain().- Protect script-only execution with the
__name__ == "__main__" guard.- Use leading underscores for internal helpers (e.g.,
_helper()).- Optionally add a test mode (e.g., via
--test) that reads from stdin and exercises functions for quick regression checks.
What are common ways to distribute Python applications?
- Wheels: the standard packaging format for libraries/apps; see the Python Packaging User Guide.- zipapp/pex: package multi-module apps into executable zip archives (zipapp in stdlib; pex via pip) using
__main__.py as the entry point.- py2exe (Windows) and py2app (macOS): build standalone executables for systems without Python installed.
- freeze: converts Python to C sources compiled to a platform-specific executable; more complex and platform-bound.
The Quick Python Book, Fourth Edition ebook for free