PYTHON · PYTHON FOR EVERYONE · CHAPTER 21

Distributing applications

Package your tool so other people can install it with a single command.

10 min readCourse: Python for EveryoneLevel: beginner

From point A to point B

Point A: your tool works on your machine, but to share it you send a ZIP with instructions like "copy this here and run that". Point B: by the end of this chapter, you'll package your code with pyproject.toml and build a wheel. You'll also install it with pip, publish it to TestPyPI and generate a single-file executable.

This is the chapter where Python has changed the most since the book was written. You'll see what remains of the original ideas and what today's workflow looks like.

From distutils and setuptools to modern packaging

Packaging an application means preparing it so other people can install it with one command, without copying files by hand. The book presented 2 tools for this.

  • distutils came in the standard library. Each project had a setup.py script that called setup() with the name, version, author and files to install. Commands such as python setup.py install, sdist or bdist installed or generated packages.
  • setuptools extended distutils. It added egg packages, dependency declarations with install_requires, the find_packages() function and the easy_install installer, which downloaded packages from PyPI.

The ideas still hold: metadata, dependencies, a source distribution and a ready-to-install distribution. What changed are the tools and the format.

Python 3.14 update. distutils was deprecated in Python 3.10 and removed in 3.12 (PEP 632); in 3.14, import distutils raises ModuleNotFoundError. setuptools is still alive, but as a build backend: you no longer run setup.py directly, because python setup.py install is deprecated and easy_install was removed in setuptools 80 (2025). Eggs are a thing of the past too: PyPI stopped accepting them (PEP 715, 2023), and today the binary format is the wheel. You install with pip and describe the project in pyproject.toml (PEP 621).

Virtual environments with venv

Before installing anything, create a virtual environment. It's a directory with its own interpreter and its own packages, isolated from the system Python. That way, each project has its own dependency versions and you don't break other tools.

$ python -m venv .venv                 # creates the environment in the .venv folder
$ source .venv/bin/activate            # Linux and macOS
$ .venv\Scripts\activate               # Windows
(.venv) $ python -m pip install --upgrade pip
(.venv) $ deactivate                   # leaves the environment

With the environment active, python and pip point to that environment. The venv module comes in the standard library and installs pip inside every new environment.

Always use python -m pip instead of plain pip. That way, you make sure you install into the interpreter you think you're using.

The structure of an installable project

You're going to package a small tool: net-inventory, which reads a CSV of routers and lists them. This is the recommended structure, called the src layout:

net-inventory/
├── LICENSE
├── README.md
├── pyproject.toml
└── src/
    └── net_inventory/
        ├── __init__.py
        ├── cli.py
        └── inventory.py

Putting the package inside src/ avoids a common mistake: your tests importing the code from the project folder instead of the installed package. Notice the names. The project uses a hyphen (net-inventory) and the Python package uses an underscore (net_inventory), because a module name can't contain hyphens.

# src/net_inventory/__init__.py
"""Tools for reading network inventories."""

__version__ = "0.1.0"
# src/net_inventory/inventory.py
"""Reading the CSV inventory."""


def load_inventory(path):
    """Reads a hostname,ip CSV and returns a dictionary."""
    devices = {}
    with open(path, encoding="utf-8") as csv_file:
        for line in csv_file:
            if line.strip():
                hostname, ip = line.strip().split(",")
                devices[hostname] = ip
    return devices
# src/net_inventory/cli.py
"""Command-line entry point."""

import sys

from net_inventory.inventory import load_inventory


def main():
    if len(sys.argv) != 2:
        print("Usage: net-inventory FILE.csv")
        return 2
    for hostname, ip in load_inventory(sys.argv[1]).items():
        print(f"{hostname:<12} {ip}")
    return 0


if __name__ == "__main__":
    sys.exit(main())

pyproject.toml: metadata and dependencies

The old setup.py was a program. pyproject.toml is a data file in TOML format: any tool can read it without running code. It has 2 main tables.

[build-system]
requires = ["setuptools>=77"]
build-backend = "setuptools.build_meta"

[project]
name = "net-inventory"
version = "0.1.0"
description = "Lists the routers in a CSV inventory"
readme = "README.md"
requires-python = ">=3.10"
license = "MIT"
authors = [{ name = "Your Name", email = "you@example.com" }]
dependencies = []

[project.optional-dependencies]
test = ["pytest>=8"]

[project.scripts]
net-inventory = "net_inventory.cli:main"

[project.urls]
Homepage = "https://example.com/net-inventory"

[build-system] says which tool builds the package: the build backend. Here it's setuptools, but you could use another one, such as hatchling, flit-core or pdm-backend. [project] holds the metadata, with names defined by a standard shared by all backends.

This table maps the setup() arguments the book taught to their current equivalent:

In setup() (book)In pyproject.toml
name, version, descriptionThe same names in [project]
long_descriptionreadme = "README.md"
author, author_emailauthors = [{ name = …, email = … }]
maintainer, maintainer_emailmaintainers = [{ name = …, email = … }]
url, download_urlThe [project.urls] table
licenselicense = "MIT" (SPDX expression, PEP 639)
scriptsThe [project.scripts] table
packages, py_modules, find_packages()The backend's automatic discovery (here, everything in src/)
install_requiresdependencies
extras_requireThe [project.optional-dependencies] table
setup_requiresrequires in [build-system]

Dependencies use the same version operators the book showed, with a clearer syntax. To ask for version 1.0 or later, but earlier than 2.0, you separate the conditions with a comma: "netmiko>=4.0,<5".

C extensions (ext_modules) are still possible with setuptools, but they're beyond the scope of this beginner course.

Console scripts (entry points)

The book copied .py files to the scripts folder with the scripts argument. Today, you declare console scripts, also called entry points: a command name that points to a function.

[project.scripts]
net-inventory = "net_inventory.cli:main"

When you install the package, pip creates an executable called net-inventory that imports net_inventory.cli and calls main(). The value main() returns is used as the exit code. It works the same on Linux, macOS and Windows, where pip generates a small .exe that launches your function.

Building an sdist and a wheel with python -m build

To distribute your project, you generate 2 files:

  • sdist (source distribution): a .tar.gz with your code and the metadata. Whoever installs it builds it on their machine.
  • wheel (built distribution): a .whl, which is a ZIP ready to install with no build steps. It's the successor to eggs and to the book's bdist.

The standard tool to build them is build, from the PyPA. You install it in your environment and run it from the project folder:

(.venv) $ python -m pip install build
(.venv) $ python -m build
* Creating isolated environment: venv+pip...
* Installing packages in isolated environment:
* Getting build dependencies for sdist...
* Building sdist...
* Building wheel from sdist
…
Successfully built net_inventory-0.1.0.tar.gz and net_inventory-0.1.0-py3-none-any.whl

build creates an isolated environment, installs the backend that [build-system] asks for, and generates both files in dist/. If you only want one, use --sdist or --wheel.

The wheel's name tells a story: py3 means it works with any Python 3, none that it doesn't depend on a specific ABI and any that it runs on any platform. You can see its contents because it's a ZIP:

$ python -m zipfile -l dist/net_inventory-0.1.0-py3-none-any.whl
File Name                                             Modified             Size
net_inventory/__init__.py                      …                 68
net_inventory/cli.py                           …                363
net_inventory/inventory.py                     …                361
net_inventory-0.1.0.dist-info/licenses/LICENSE …               1066
net_inventory-0.1.0.dist-info/METADATA         …                483
net_inventory-0.1.0.dist-info/WHEEL            …                 91
net_inventory-0.1.0.dist-info/entry_points.txt …                 57
net_inventory-0.1.0.dist-info/top_level.txt    …                 14
net_inventory-0.1.0.dist-info/RECORD           …                763
Python 3.14 update. The book chose among many formats with sdist --formats (.zip, .tar.bz2, .tar.Z…) and bdist --formats (RPM, Windows installer). Those commands disappeared along with distutils. Today there are only 2 standard formats for PyPI: the sdist as .tar.gz and the wheel. System packages (.deb, .rpm) are prepared by the distributions with their own tools.

Installing with pip

Test your wheel the way someone else would: in a clean virtual environment.

$ python -m venv /tmp/trial
$ source /tmp/trial/bin/activate
(trial) $ python -m pip install dist/net_inventory-0.1.0-py3-none-any.whl
(trial) $ net-inventory routers.csv
r1-lima      10.0.0.1
r2-quito     10.0.0.2
(trial) $ net-inventory
Usage: net-inventory FILE.csv
(trial) $ echo $?
2

While you're developing, you don't need to rebuild the wheel after every change. Install the project in editable mode: pip links your src/ folder, and changes show up instantly.

(.venv) $ python -m pip install -e .
(.venv) $ python -m pip install -e ".[test]"    # includes the optional dependencies

To uninstall, use python -m pip uninstall net-inventory. pip also removes the command it created.

Publishing to TestPyPI with twine

PyPI (the Python Package Index) is the public repository pip downloads packages from. Before publishing there, rehearse on TestPyPI, a separate instance meant for testing. You need an account on test.pypi.org and an API token created in your account settings.

The project name must be unique on the index. If net-inventory already exists, choose another one in pyproject.toml and rebuild.

(.venv) $ python -m pip install twine
(.venv) $ python -m twine check dist/*
Checking dist/net_inventory-0.1.0-py3-none-any.whl: PASSED
Checking dist/net_inventory-0.1.0.tar.gz: PASSED
(.venv) $ python -m twine upload --repository testpypi dist/*

twine check validates the metadata and checks that the README can be rendered on the index website. twine upload asks for your token; never store it in your code repository. After that, anyone can install your package from TestPyPI:

$ python -m pip install --index-url https://test.pypi.org/simple/ --no-deps net-inventory

When everything works, you publish to PyPI with python -m twine upload dist/*. To automate it from GitHub Actions, there's trusted publishing, which saves you from handling tokens by hand.

Python 3.14 update. The book registered the project with setup.py register and uploaded with setup.py sdist upload, storing the username and password in ~/.pypirc. Those commands no longer exist. Today you build with build, upload with twine and authenticate with API tokens or trusted publishing.

Executables: zipapp, PyInstaller and py2exe

A wheel requires the person to have Python installed. If you want to hand over a single file, you have 2 paths depending on your audience.

zipapp comes in the standard library. It packs your code into a .pyz file that Python runs directly. It still needs an interpreter, but you distribute a single file:

$ mkdir app && cp -r src/net_inventory app/
$ python -m zipapp app -m "net_inventory.cli:main" -o net-inventory.pyz -p "/usr/bin/env python3"
$ python net-inventory.pyz routers.csv
r1-lima      10.0.0.1
r2-quito     10.0.0.2
$ ./net-inventory.pyz routers.csv        # on Linux and macOS, thanks to -p

The -m option sets the entry function, and -p adds the line that says which interpreter to use. One detail: zipapp calls main() but ignores what it returns. If you need an exit code, call sys.exit() inside the function. If your tool has dependencies, you can install them into the folder before packaging with python -m pip install --target app package.

PyInstaller is a third-party package that goes further. It analyzes your code, gathers the modules it uses and bundles them together with a Python interpreter. The result runs on machines that don't have Python:

(.venv) $ python -m pip install pyinstaller
(.venv) $ pyinstaller --onefile --name net-inventory src/net_inventory/cli.py
…
INFO: Build complete! The results are available in: …/dist
(.venv) $ ./dist/net-inventory routers.csv
r1-lima      10.0.0.1
r2-quito     10.0.0.2

With --onefile, you get a single executable; without that option, a folder with the executable and its libraries. PyInstaller doesn't cross-compile: for a Windows .exe, run it on Windows. The executables are fairly large, because they carry the interpreter inside; the one in this example takes up about 12 MB on Linux.

Python 3.14 update. The book used py2exe as a distutils extension, with python setup.py py2exe and options such as bundle_files and zipfile=None. py2exe still exists for Windows and supports Python 3.14, but it no longer depends on distutils: its current interface is the py2exe.freeze() function. Also, bundle_files values below 3 don't work since Python 3.12, and zipfile=None is deprecated. To get started, PyInstaller is the most widespread option, and it works on Windows, macOS and Linux.

Challenge

Answer before you open the solution.

1. An old tutorial starts with from distutils.core import setup. What happens in Python 3.14, and what do you do?

It fails with ModuleNotFoundError. distutils was removed in 3.12. Describe the project in pyproject.toml with a backend such as setuptools, and build with python -m build.

2. Where do you declare that your tool needs netmiko 4.x?

In dependencies in the [project] table: dependencies = ["netmiko>=4,<5"]. It's the successor to install_requires.

3. What's the difference between the sdist and the wheel?

The sdist is source code that has to be built; the wheel is already built. pip installs a wheel without running build steps, which is why it's faster and more predictable.

4. You want the backup-configs command to exist when your package is installed. What do you add?

An entry in [project.scripts]: backup-configs = "my_package.cli:main". pip creates the executable at install time.

5. Your client uses Windows without Python and wants an .exe. Which tool do you use, and where do you run it?

PyInstaller, on a Windows machine. zipapp would need an installed interpreter, and PyInstaller doesn't generate executables for another operating system.

Key takeaways

  • distutils no longer exists and setup.py install is deprecated; you describe the project in pyproject.toml.
  • [build-system] picks the backend (setuptools or another); [project] holds the name, version, authorship, license and dependencies.
  • Always work in a virtual environment created with python -m venv and install with python -m pip.
  • python -m build generates the sdist and the wheel; twine checks them and uploads them to TestPyPI or PyPI.
  • [project.scripts] turns a function into a terminal command.
  • For a single file: zipapp if Python is installed, PyInstaller if it isn't.

With this chapter, you finish "Python for Everyone". You've gone through the language from your first variable to a package other people can install. It takes practice: go back to the examples, change them and apply them to your own network. The next topic in the network programmability path will be Ansible (coming soon), where you'll automate the configuration of many devices at once.

Official resources

Source and credits. This course is based on the book Python para todos by Raúl González Duque, published under the Creative Commons Attribution 2.5 Spain license. The original book was written for Python 2.5. Jesús Espinoza, with AI assistance, brought it to Python 3.14: he rewrote every chapter in his own words, replaced the examples with networking cases, updated the syntax and the modules that no longer exist, fixed errors in the original and tested all the code with Python 3.14.6 against the official documentation.

Navigate