| 1 |
# Packaging Entry Points |
| 2 |
|
| 3 |
```{eval-rst} |
| 4 |
.. currentmodule:: click |
| 5 |
``` |
| 6 |
|
| 7 |
It's recommended to write command line utilities as installable packages with |
| 8 |
entry points instead of telling users to run ``python hello.py``. |
| 9 |
|
| 10 |
A distribution package is a ``.whl`` file you install with pip or another Python |
| 11 |
installer. You use a ``pyproject.toml`` file to describe the project and how it |
| 12 |
is built into a package. You might upload this package to PyPI, or distribute it |
| 13 |
to your users in another way. |
| 14 |
|
| 15 |
Python installers create executable scripts that will run a specified Python |
| 16 |
function. These are known as "entry points". The installer knows how to create |
| 17 |
an executable regardless of the operating system, so it will work on Linux, |
| 18 |
Windows, MacOS, etc. |
| 19 |
|
| 20 |
## Project Files |
| 21 |
|
| 22 |
To install your app with an entry point, all you need is the script and a |
| 23 |
``pyproject.toml`` file. Here's an example project directory: |
| 24 |
|
| 25 |
```text |
| 26 |
hello-project/ |
| 27 |
src/ |
| 28 |
hello/ |
| 29 |
__init__.py |
| 30 |
hello.py |
| 31 |
pyproject.toml |
| 32 |
``` |
| 33 |
|
| 34 |
Contents of ``hello.py``: |
| 35 |
|
| 36 |
```{eval-rst} |
| 37 |
.. click:example:: |
| 38 |
import click |
| 39 |
|
| 40 |
@click.command() |
| 41 |
def cli(): |
| 42 |
"""Prints a greeting.""" |
| 43 |
click.echo("Hello, World!") |
| 44 |
``` |
| 45 |
|
| 46 |
Contents of ``pyproject.toml``: |
| 47 |
|
| 48 |
```toml |
| 49 |
[project] |
| 50 |
name = "hello" |
| 51 |
version = "1.0.0" |
| 52 |
description = "Hello CLI" |
| 53 |
requires-python = ">=3.11" |
| 54 |
dependencies = [ |
| 55 |
"click>=8.1", |
| 56 |
] |
| 57 |
|
| 58 |
[project.scripts] |
| 59 |
hello = "hello.hello:cli" |
| 60 |
|
| 61 |
[build-system] |
| 62 |
requires = ["flit_core<4"] |
| 63 |
build-backend = "flit_core.buildapi" |
| 64 |
``` |
| 65 |
|
| 66 |
The magic is in the ``project.scripts`` section. Each line identifies one executable |
| 67 |
script. The first part before the equals sign (``=``) is the name of the script that |
| 68 |
should be generated, the second part is the import path followed by a colon |
| 69 |
(``:``) with the function to call (the Click command). |
| 70 |
|
| 71 |
## Installation |
| 72 |
|
| 73 |
When your package is installed, the installer will create an executable script |
| 74 |
based on the configuration. During development, you can install in editable |
| 75 |
mode using the ``-e`` option. Remember to use a virtual environment! |
| 76 |
|
| 77 |
```console |
| 78 |
$ python -m venv .venv |
| 79 |
$ . .venv/bin/activate |
| 80 |
$ pip install -e . |
| 81 |
``` |
| 82 |
|
| 83 |
Afterwards, your command should be available: |
| 84 |
|
| 85 |
```console |
| 86 |
$ hello |
| 87 |
Hello, World! |
| 88 |
``` |