In this lesson, you’ll learn how to transform your internal Python functions into professional, system-wide command-line tools using pyproject.toml.
Bridging Python Functions to the Terminal
When you distribute a Python package, you often want users to run a command (like my-app) rather than forcing them to write python -m my_package.main. By defining entry points, you instruct the packaging system to create a small executable script in the user's environment that maps a CLI command directly to a specific function in your code.
Configuring in pyproject.toml
Modern Python packaging relies on the [project.scripts] table within your pyproject.toml file. The format is simple: command-name = "package.module:function".
Imagine you have a file structure using the src layout where your core logic resides in src/my_cli/cli.py:
# src/my_cli/cli.py
def main():
print("Hello from your custom CLI!")
To expose this as a terminal command, add this to your pyproject.toml:
[project.scripts]
my-tool = "my_cli.cli:main"
How It Works
- The Mapping: The left side (
my-tool) is the name of the command you want the user to type in their terminal. - The Destination: The right side points to the entry point. The colon
:separates the module path from the function name. - Execution: When a user installs your package (e.g., via
pip install .), the installer detects this entry point and automatically generates a platform-specific script (a.exeon Windows, or a shebang-based script on Unix) in the user’sbinorScriptsfolder.
Because these folders are typically on the system PATH, the user can simply open their terminal and type my-tool, which triggers the main() function inside your package instantly. This approach abstracts away the complexity of your file structure, providing a clean, professional interface for anyone using your library.
Key Takeaway: Use the [project.scripts] table in pyproject.toml to map custom terminal commands directly to Python functions, enabling users to run your package as a standalone application without manual execution paths.