Let’s create a “hello, world” distributable that creates a CLI executable,
greet
: first, some preparation:
$ mkdir hello-world
$ cd hello-world
$ python -m venv hello-world # create a virtual environment, hello-world
$ hello-world/Scripts/activate # activate the virtual environment
$ mkdir -p src/hello/scripts
$ touch src/hello/__init__.py
Create the greet
function in src/hello/__init__.py
:
|
|
Nothing earth-shattering for our purpose here. Next, create the CLI script
that calls greet
when an argument is given on the command line:
|
|
Note the function name main
: it’s an arbitrary name but one that
setup.cfg
1 references so build
can generate the
executable. Next, let’s create a minimal setup.cfg
.
|
|
A few notable points:
- Lines 4-6 are necessary when using a
src/
layout - Lines 11-13 specifies the CLI command
build
should generate in the virtual environment’sScripts
directory- Line 13 takes the form of
executable-name = package.module:function
; in this case, the executable’s name isgreet
and it invokes the functionmain
in modulehello.scripts.cli
.
- Line 13 takes the form of
Next, create pyproject.toml
that build
relies on to build the distributable:
|
|
Finally, it’s time to build the distributable:
$ pip install build # installs the build tool
$ python -m build --wheel # builds only the wheel distribution
All’s done. To test this, create another virtual environment, install
the distributable found in dist/
with pip
; this generates the executable
greet
in the environment’s Scripts/
directory. Ignoring the generated
artifacts, the directory should look like the following:
hello-world
├── pyproject.toml
├── setup.cfg
└── src
└── hello
├── __init__.py
└── scripts
└── cli.py
-
According to Configuring metadata,
setup.cfg
is the preferred format. ↩︎