Move Exceptions and Entry-points docs from reST to MyST (#3142)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents 934cba0, 1a1cdcb · Browse files · 4 files·+224 added−213 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+224 added−213 removed
- other:+224 added−213 removed
Provenance
- Commit
7f7bbe4- Tree
260e863- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
934cba0- Parent 2
1a1cdcb
4 files changed+224 added−213 removed
added:docs/entry-points.md+88 added
1+# Packaging Entry Points2+3+```{eval-rst}4+.. currentmodule:: click5+```6+7+It's recommended to write command line utilities as installable packages with8+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 Python11+installer. You use a ``pyproject.toml`` file to describe the project and how it12+is built into a package. You might upload this package to PyPI, or distribute it13+to your users in another way.14+15+Python installers create executable scripts that will run a specified Python16+function. These are known as "entry points". The installer knows how to create17+an executable regardless of the operating system, so it will work on Linux,18+Windows, MacOS, etc.19+20+## Project Files21+22+To install your app with an entry point, all you need is the script and a23+``pyproject.toml`` file. Here's an example project directory:24+25+```text26+hello-project/27+ src/28+ hello/29+ __init__.py30+ hello.py31+ pyproject.toml32+```33+34+Contents of ``hello.py``:35+36+```{eval-rst}37+.. click:example::38+ import click39+40+ @click.command()41+ def cli():42+ """Prints a greeting."""43+ click.echo("Hello, World!")44+```45+46+Contents of ``pyproject.toml``:47+48+```toml49+[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 executable67+script. The first part before the equals sign (``=``) is the name of the script that68+should be generated, the second part is the import path followed by a colon69+(``:``) with the function to call (the Click command).70+71+## Installation72+73+When your package is installed, the installer will create an executable script74+based on the configuration. During development, you can install in editable75+mode using the ``-e`` option. Remember to use a virtual environment!76+77+```console78+$ python -m venv .venv79+$ . .venv/bin/activate80+$ pip install -e .81+```82+83+Afterwards, your command should be available:84+85+```console86+$ hello87+Hello, World!88+```deleted:docs/entry-points.rst-87 removed
1-Packaging Entry Points2-======================3-4-It's recommended to write command line utilities as installable packages with5-entry points instead of telling users to run ``python hello.py``.6-7-A distribution package is a ``.whl`` file you install with pip or another Python8-installer. You use a ``pyproject.toml`` file to describe the project and how it9-is built into a package. You might upload this package to PyPI, or distribute it10-to your users in another way.11-12-Python installers create executable scripts that will run a specified Python13-function. These are known as "entry points". The installer knows how to create14-an executable regardless of the operating system, so it will work on Linux,15-Windows, MacOS, etc.16-17-18-Project Files19--------------20-21-To install your app with an entry point, all you need is the script and a22-``pyproject.toml`` file. Here's an example project directory:23-24-.. code-block:: text25-26- hello-project/27- src/28- hello/29- __init__.py30- hello.py31- pyproject.toml32-33-Contents of ``hello.py``:34-35-.. click:example::36-37- import click38-39- @click.command()40- def cli():41- """Prints a greeting."""42- click.echo("Hello, World!")43-44-Contents of ``pyproject.toml``:45-46-.. code-block:: toml47-48- [project]49- name = "hello"50- version = "1.0.0"51- description = "Hello CLI"52- requires-python = ">=3.11"53- dependencies = [54- "click>=8.1",55- ]56-57- [project.scripts]58- hello = "hello.hello:cli"59-60- [build-system]61- requires = ["flit_core<4"]62- build-backend = "flit_core.buildapi"63-64-The magic is in the ``project.scripts`` section. Each line identifies one executable65-script. The first part before the equals sign (``=``) is the name of the script that66-should be generated, the second part is the import path followed by a colon67-(``:``) with the function to call (the Click command).68-69-70-Installation71-------------72-73-When your package is installed, the installer will create an executable script74-based on the configuration. During development, you can install in editable75-mode using the ``-e`` option. Remember to use a virtual environment!76-77-.. code-block:: console78-79- $ python -m venv .venv80- $ . .venv/bin/activate81- $ pip install -e .82-83-Afterwards, your command should be available:84-85-.. click:run::86-87- invoke(cli, prog_name="hello")added:docs/exceptions.md+136 added
1+(exception-handling-exit-codes)=2+3+# Exception Handling and Exit Codes4+5+```{eval-rst}6+.. currentmodule:: click7+```8+9+Click internally uses exceptions to signal various error conditions that10+the user of the application might have caused. Primarily this is things11+like incorrect usage.12+13+```{contents}14+:depth: 115+:local:16+```17+18+## Where are Errors Handled?19+20+Click's main error handling is happening in {meth}`Command.main`. In21+there it handles all subclasses of {exc}`ClickException` as well as the22+standard {exc}`EOFError` and {exc}`KeyboardInterrupt` exceptions. The23+latter are internally translated into an {exc}`Abort`.24+25+The logic applied is the following:26+27+1. If an {exc}`EOFError` or {exc}`KeyboardInterrupt` happens, reraise it28+ as {exc}`Abort`.29+2. If a {exc}`ClickException` is raised, invoke the30+ {meth}`ClickException.show` method on it to display it and then exit31+ the program with {attr}`ClickException.exit_code`.32+3. If an {exc}`Abort` exception is raised print the string ``Aborted!``33+ to standard error and exit the program with exit code ``1``.34+4. If it goes through well, exit the program with exit code ``0``.35+36+## What if I Don't Want That?37+38+Generally you always have the option to invoke the {meth}`Command.invoke`39+method yourself. For instance if you have a {class}`Command` you can40+invoke it manually like this:41+42+```python43+ctx = command.make_context("command-name", ["args", "go", "here"])44+with ctx:45+ result = command.invoke(ctx)46+```47+48+In this case exceptions will not be handled at all and bubbled up as you49+would expect.50+51+Starting with Click 3.0 you can also use the {meth}`Command.main` method52+but disable the standalone mode which will do two things: disable53+exception handling and disable the implicit {func}`sys.exit` at the end.54+55+So you can do something like this:56+57+```python58+command.main(59+ ["command-name", "args", "go", "here"],60+ standalone_mode=False,61+)62+```63+64+## Which Exceptions Exist?65+66+Click has two exception bases: {exc}`ClickException` which is raised for67+all exceptions that Click wants to signal to the user and {exc}`Abort`68+which is used to instruct Click to abort the execution.69+70+A {exc}`ClickException` has a {meth}`ClickException.show` method which71+can render an error message to stderr or the given file object. If you72+want to use the exception yourself for doing something check the API docs73+about what else they provide.74+75+The following common subclasses exist:76+77+- {exc}`UsageError` to inform the user that something went wrong.78+- {exc}`BadParameter` to inform the user that something went wrong with79+ a specific parameter. These are often handled internally in Click and80+ augmented with extra information if possible. For instance if those81+ are raised from a callback Click will automatically augment it with82+ the parameter name if possible.83+- {exc}`FileError` this is an error that is raised by the84+ {class}`FileType` if Click encounters issues opening the file.85+86+(help-page-exit-codes)=87+88+## Help Pages and Exit Codes89+90+Triggering the a help page intentionally (by passing in ``--help``)91+returns exit code 0. If a help page is displayed due to incorrect user92+input, the program returns exit code 2. See {ref}`exit-codes` for more93+general information.94+95+For clarity, here is an example.96+97+```{eval-rst}98+.. click:example::99+100+ @click.group('printer_group')101+ def printer_group():102+ pass103+104+ @printer_group.command('printer')105+ @click.option('--this')106+ def printer(this):107+ if this:108+ click.echo(this)109+110+.. click:run::111+ invoke(printer_group, args=['--help'])112+113+The above invocation returns exit code 0.114+115+.. click:run::116+ invoke(printer_group, args=[])117+```118+119+The above invocation returns exit code 2 since the user invoked the command incorrectly. However, since this is such a common error when first using a command, Click invokes the help page for the user. To see that `printer-group` is an invalid invocation, turn `no_args_is_help` off.120+121+```{eval-rst}122+.. click:example::123+124+ @click.group('printer_group', no_args_is_help=False)125+ def printer_group():126+ pass127+128+ @printer_group.command('printer')129+ @click.option('--this')130+ def printer(this):131+ if this:132+ click.echo(this)133+134+.. click:run::135+ invoke(printer_group, args=[])136+```deleted:docs/exceptions.rst-126 removed
1-.. _exception-handling-exit-codes:2-3-Exception Handling and Exit Codes4-==================================5-6-.. currentmodule:: click7-8-Click internally uses exceptions to signal various error conditions that9-the user of the application might have caused. Primarily this is things10-like incorrect usage.11-12-.. contents::13- :depth: 114- :local:15-16-Where are Errors Handled?17--------------------------18-19-Click's main error handling is happening in :meth:`Command.main`. In20-there it handles all subclasses of :exc:`ClickException` as well as the21-standard :exc:`EOFError` and :exc:`KeyboardInterrupt` exceptions. The22-latter are internally translated into an :exc:`Abort`.23-24-The logic applied is the following:25-26-1. If an :exc:`EOFError` or :exc:`KeyboardInterrupt` happens, reraise it27- as :exc:`Abort`.28-2. If a :exc:`ClickException` is raised, invoke the29- :meth:`ClickException.show` method on it to display it and then exit30- the program with :attr:`ClickException.exit_code`.31-3. If an :exc:`Abort` exception is raised print the string ``Aborted!``32- to standard error and exit the program with exit code ``1``.33-4. If it goes through well, exit the program with exit code ``0``.34-35-What if I don't want that?36---------------------------37-38-Generally you always have the option to invoke the :meth:`invoke` method39-yourself. For instance if you have a :class:`Command` you can invoke it40-manually like this::41-42- ctx = command.make_context('command-name', ['args', 'go', 'here'])43- with ctx:44- result = command.invoke(ctx)45-46-In this case exceptions will not be handled at all and bubbled up as you47-would expect.48-49-Starting with Click 3.0 you can also use the :meth:`Command.main` method50-but disable the standalone mode which will do two things: disable51-exception handling and disable the implicit :meth:`sys.exit` at the end.52-53-So you can do something like this::54-55- command.main(['command-name', 'args', 'go', 'here'],56- standalone_mode=False)57-58-Which Exceptions Exist?59------------------------60-61-Click has two exception bases: :exc:`ClickException` which is raised for62-all exceptions that Click wants to signal to the user and :exc:`Abort`63-which is used to instruct Click to abort the execution.64-65-A :exc:`ClickException` has a :meth:`~ClickException.show` method which66-can render an error message to stderr or the given file object. If you67-want to use the exception yourself for doing something check the API docs68-about what else they provide.69-70-The following common subclasses exist:71-72-* :exc:`UsageError` to inform the user that something went wrong.73-* :exc:`BadParameter` to inform the user that something went wrong with74- a specific parameter. These are often handled internally in Click and75- augmented with extra information if possible. For instance if those76- are raised from a callback Click will automatically augment it with77- the parameter name if possible.78-* :exc:`FileError` this is an error that is raised by the79- :exc:`FileType` if Click encounters issues opening the file.80-81-82-.. _help-page-exit-codes:83-84-Help Pages and Exit Codes85---------------------------86-87-Triggering the a help page intentionally (by passing in ``--help``) returns exit code 0. If a help page is displayed due to incorrect user input, the program returns exit code 2. See :ref:`exit-codes` for more general information.88-89-For clarity, here is an example.90-91-.. click:example::92-93- @click.group('printer_group')94- def printer_group():95- pass96-97- @printer_group.command('printer')98- @click.option('--this')99- def printer(this):100- if this:101- click.echo(this)102-103-.. click:run::104- invoke(printer_group, args=['--help'])105-106-The above invocation returns exit code 0.107-108-.. click:run::109- invoke(printer_group, args=[])110-111-The above invocation returns exit code 2 since the user invoked the command incorrectly. However, since this is such a common error when first using a command, Click invokes the help page for the user. To see that `printer-group` is an invalid invocation, turn `no_args_is_help` off.112-113-.. click:example::114-115- @click.group('printer_group', no_args_is_help=False)116- def printer_group():117- pass118-119- @printer_group.command('printer')120- @click.option('--this')121- def printer(this):122- if this:123- click.echo(this)124-125-.. click:run::126- invoke(printer_group, args=[])