Sub topic 14
Installing the tool as a command
So far you have run the tool as python greet.py Ada. Users expect to type greet Ada from any directory. This chapter shows how to make that work with a pyproject.toml entry point, what the installer generates, and which mistakes cause most failures.
Prerequisites
This chapter assumes you can:
- Create and activate a virtual environment, and run
pip install. - Write a
main(argv=None)function that returns an integer exit code, as in the earlier chapter on structuring the program. - Read a basic TOML file.
What "installing a command" means
A console command is a small executable file in a directory on your PATH. The shell finds it by name and runs it. When you install a package with a console entry point, pip creates that file for you. It sits in the bin directory of the active virtual environment (Scripts on Windows), and it imports your function and calls it.
You do not write the executable yourself. You declare the entry point, and the installer generates the file.
Project layout
Keep the layout minimal. This chapter uses one module next to pyproject.toml:
greet-project/
├── pyproject.toml
├── greet.py
└── tests/
└── test_greet.pygreet.py is the program from earlier chapters. It defines build_parser() and main(argv=None), and ends with the if __name__ == "__main__": guard.
Declaring the entry point
Create pyproject.toml:
[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"
[project]
name = "greet"
version = "0.1.0"
description = "Print a greeting."
requires-python = ">=3.9"
[project.scripts]
greet = "greet:main"
[tool.setuptools]
py-modules = ["greet"]Each section does one job:
[build-system]tells pip which backend builds the project. Without it, pip falls back to legacy behavior. Setuptools 61 is the first version that reads the[project]table.[project]holds the metadata.nameandversionare required.[project.scripts]maps a command name to an entry point. Heregreetis the command, andgreet:mainmeans "import modulegreet, then use its attributemain".[tool.setuptools]names the module to include. Setuptools can often discover a single module itself, but naming it avoids surprises.
The entry point format is module.path:callable. For a package, you would write something like greet.cli:main, where greet/cli.py defines main.
Installing and running
Create a virtual environment, activate it, and install the project in editable mode:
python -m venv .venv
source .venv/bin/activate
python -m pip install -e .On Windows, activate with .venv\Scripts\activate instead.
The command now exists:
greet Ada --count 2
which greet
greet Ada --count many
echo $?Expected behavior:
Hello, Ada!
Hello, Ada!
/path/to/greet-project/.venv/bin/greet
usage: greet [-h] [-c COUNT] [-v] name
greet: error: argument -c/--count: invalid int value: 'many'
2The last line is the exit status that argparse chose for a usage error. It reaches the shell because the wrapper hands your exit code to sys.exit.
What the generated wrapper does
The wrapper is a short script, roughly:
import sys
from greet import main
if __name__ == "__main__":
sys.exit(main())The real file also contains a shebang line pointing at the environment's Python interpreter, so the command runs with the right interpreter and the right installed packages. That is the main advantage over copying greet.py into /usr/local/bin.
The wrapper calls main() with no arguments. This is why the main(argv=None) pattern matters. With argv=None, parse_args falls back to sys.argv[1:], so the real command-line arguments are used. In tests you pass a list instead, and the same function works in both places.
Exit codes and return values
sys.exit(value) treats its argument differently depending on type:
| Value returned by `main` | Resulting behavior |
|---|---|
| `0` or `None` | Exit status 0 (success) |
| Another integer, such as `1` | That exit status |
| A string | The string is printed to stderr and the status is 1 |
| Anything else | The object is printed to stderr and the status is 1 |
A function that forgets its return statement returns None, which looks like success. If your tool reports an error but still exits with 0, check every path through main for a missing return.
Editable versus regular installs
pip install -e . creates an editable install. Python imports greet from your working directory, so edits to greet.py take effect immediately. pip install . copies the module into site-packages, and you must reinstall after each change.
Changes to pyproject.toml are different. The wrapper script is generated at install time, so even with an editable install you must rerun pip install -e . after you rename the command or change the entry point target.
Running without installing
Two other ways to run the code are useful during development:
python greet.py Ada
python -m greet AdaBoth work because of the if __name__ == "__main__": guard. The -m form runs the module by import name, so it needs to be run from a directory where greet is importable. For a package, you can add a __main__.py file so that python -m greet runs it. A typical __main__.py contains:
import sys
from greet.cli import main
sys.exit(main())The program name in usage messages
argparse builds the usage: line from prog. If you do not set prog, it uses sys.argv[0]. Under an installed command that is the command name, which is usually what you want. Under python -m greet, it is __main__.py, which is not.
The tool from earlier chapters sets prog="greet" explicitly. Doing this makes usage text and help output identical however the program is started. Set it unless you want the name to follow the invocation.
Common errors
greet: command not found. The virtual environment is not active, or the environment'sbindirectory is not onPATH. Runwhich greet, or call.venv/bin/greetdirectly to confirm the file exists.ModuleNotFoundError: No module named 'greet'when running the command. The module was not included in the install. Checkpy-modules(orpackages) in[tool.setuptools], and check that the name matches the file name.TypeError: main() missing 1 required positional argument. The entry point function must be callable with no arguments. Giveargva default ofNone.- Entry point name collisions. If another installed package already provides a command called
greet, the one installed last wins. Pick a distinctive command name, and check withwhich -a greet. - Stale wrapper after edits. See the warning above. Reinstall.
- Wrong exit status. A missing
return, or returning a string where you meant an integer, changes what the shell sees.
Distributing to other people
For a tool you want others to use, two installers are common:
pipx install .(orpipx install greetonce published) installs the command into its own isolated environment and puts it on the user'sPATH. Users do not need to manage a virtual environment, and the tool's dependencies cannot conflict with their other projects.pip install greetinto an existing environment works for libraries and for tools that are used inside a project.
You can build distributable files with python -m build, which writes a source archive and a wheel into dist/. Uploading them to a package index is a separate step that this chapter does not cover.
Choosing a command name
The entry point name is the public interface of your tool. Keep it short and lowercase, and avoid names of common system commands such as test or list. You can declare several commands from one project by adding more lines under [project.scripts], each pointing at its own function. Each function must follow the same rules: callable with no arguments, returning an exit code.
Exercise
You install your tool with pip install -e . and run greet Ada --count many. The usage error appears, but echo $? prints 0 and not 2. The entry point is greet = "greet:main", and main ends with build_parser().parse_args(argv) followed by a print loop and no return. Name two possible causes of the 0 exit status, and say which line of the project to check for each.
Show answer
Argparse exits with status 2 on a usage error by raising SystemExit, so a real parse failure should give 2. A status of 0 therefore points to one of two causes. First, the failing command may not be the one you think: an older greet earlier on PATH, or a stale wrapper, may be running different code, so check which -a greet and reinstall. Second, if the parse succeeded and the program printed its own error message, then main has no return statement, so it returns None, which sys.exit treats as 0. Check that every path in main ends with return <code>, and check that the wrapper's target in [project.scripts] matches the function you edited.