Python source distributions are typically built and installed using the standard library's distutils module. This framework allows developers to define package metadata and simplifies the installation process for end users through a standard setup.py script.
Consider a simple module named timestamp_utils.py:
import datetime
def get_current_timestamp():
return datetime.datetime.now().isoformat()
def display_greeting():
print("Welcome to the utility module.")
To package this module, create a setup.py file in the same directory:
from distutils.core import setup
setup(
name="timestamp_pkg",
version="0.1.0",
description="A basic timestamp utility package",
py_modules=['timestamp_utils'],
)
Generate the source distribution archive by executing the following command:
python setup.py sdist
This execution creates a compressed archive (e.g., timestamp_pkg-0.1.0.zip or .tar.gz) within a newly created dist/ directory. The console output will reflect the file copying and archiving process:
running sdist
running check
warning: sdist: manifest template 'MANIFEST.in' does not exist (using default file list)
writing manifest file 'MANIFEST'
creating timestamp_pkg-0.1.0
copying files to timestamp_pkg-0.1.0...
copying timestamp_utils.py -> timestamp_pkg-0.1.0
copying setup.py -> timestamp_pkg-0.1.0
creating dist
creating 'dist/timestamp_pkg-0.1.0.zip' and adding 'timestamp_pkg-0.1.0' to it
removing 'timestamp_pkg-0.1.0' (and everything under it)
To install the package from the extracted archive, run:
python setup.py install
The installation process copies the module to the site-packages directory of the active Python environment:
running install
running build
running build_py
creating build
creating build/lib
copying timestamp_utils.py -> build/lib
running install_lib
copying build/lib/timestamp_utils.py -> /path/to/python/lib/site-packages
byte-compiling /path/to/python/lib/site-packages/timestamp_utils.py to timestamp_utils.cpython-39.pyc
running install_egg_info
Writing /path/to/python/lib/site-packages/timestamp_pkg-0.1.0-py3.9.egg-info
Once installed, the module becomes available for import globally in that environment:
import timestamp_utils
print(timestamp_utils.get_current_timestamp())