In this lesson, you will learn how to transform your internal Python functions into professional, system-wide command-line tools that users can execute directly from their terminal.
The Power of Entry Points
When you build a Python package, you often write logic meant to be run as a standalone utility. Instead of forcing users to type python -m my_package.main, you can define entry points. An entry point is a mapping defined in your pyproject.toml file that tells the installer: "When the user types this command name, execute this specific function in my code."
Configuring pyproject.toml
Modern Python packaging relies on the [project.scripts] table within your pyproject.toml. This tells the packaging backend (like hatch, flit, or setuptools) to generate a small executable wrapper script automatically when the package is installed.
Imagine you have a project with a package named data_tool containing a file cli.py with a function called run(). To turn this into a terminal command named process-data, you add this to your configuration:
[project.scripts]
process-data = "data_tool.cli:run"
How it Works
- The Mapping: The left side (
process-data) is the command the user types in their terminal. The right side (data_tool.cli:run) follows the formatmodule.path:function_name. - Installation: When a user runs
pip install .oruv pip install ., the installer looks at this configuration. - The Wrapper: The installer places a small script in the user's system "bin" directory (which should be in their
PATH). - Execution: Because this wrapper is automatically linked to your Python environment, typing
process-datain the terminal will immediately trigger yourrun()function.
This approach is cleaner than requiring users to know your internal file structure. It treats your package as a professional utility, allowing you to ship powerful CLI interfaces that function just like git, pip, or pytest.
Key Takeaway: Use the [project.scripts] table in pyproject.toml to map terminal commands to Python functions, automating the creation of cross-platform executable scripts during package installation.