Skip to content
Myr

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

4 files+224 added−213 removed

added:docs/entry-points.md+88 added
1# Packaging Entry Points23```{eval-rst}4.. currentmodule:: click5```67It's recommended to write command line utilities as installable packages with8entry points instead of telling users to run ``python hello.py``.910A distribution package is a ``.whl`` file you install with pip or another Python11installer. You use a ``pyproject.toml`` file to describe the project and how it12is built into a package. You might upload this package to PyPI, or distribute it13to your users in another way.1415Python installers create executable scripts that will run a specified Python16function. These are known as "entry points". The installer knows how to create17an executable regardless of the operating system, so it will work on Linux,18Windows, MacOS, etc.1920## Project Files2122To install your app with an entry point, all you need is the script and a23``pyproject.toml`` file. Here's an example project directory:2425```text26hello-project/27 src/28 hello/29 __init__.py30 hello.py31 pyproject.toml32```3334Contents of ``hello.py``:3536```{eval-rst}37.. click:example::38 import click3940 @click.command()41 def cli():42 """Prints a greeting."""43 click.echo("Hello, World!")44```4546Contents of ``pyproject.toml``:4748```toml49[project]50name = "hello"51version = "1.0.0"52description = "Hello CLI"53requires-python = ">=3.11"54dependencies = [55 "click>=8.1",56]5758[project.scripts]59hello = "hello.hello:cli"6061[build-system]62requires = ["flit_core<4"]63build-backend = "flit_core.buildapi"64```6566The magic is in the ``project.scripts`` section. Each line identifies one executable67script. The first part before the equals sign (``=``) is the name of the script that68should be generated, the second part is the import path followed by a colon69(``:``) with the function to call (the Click command).7071## Installation7273When your package is installed, the installer will create an executable script74based on the configuration. During development, you can install in editable75mode using the ``-e`` option. Remember to use a virtual environment!7677```console78$ python -m venv .venv79$ . .venv/bin/activate80$ pip install -e .81```8283Afterwards, your command should be available:8485```console86$ hello87Hello, World!88```
deleted:docs/entry-points.rst-87 removed
1Packaging Entry Points2======================34It's recommended to write command line utilities as installable packages with5entry points instead of telling users to run ``python hello.py``.67A distribution package is a ``.whl`` file you install with pip or another Python8installer. You use a ``pyproject.toml`` file to describe the project and how it9is built into a package. You might upload this package to PyPI, or distribute it10to your users in another way.1112Python installers create executable scripts that will run a specified Python13function. These are known as "entry points". The installer knows how to create14an executable regardless of the operating system, so it will work on Linux,15Windows, MacOS, etc.161718Project Files19-------------2021To install your app with an entry point, all you need is the script and a22``pyproject.toml`` file. Here's an example project directory:2324.. code-block:: text2526 hello-project/27 src/28 hello/29 __init__.py30 hello.py31 pyproject.toml3233Contents of ``hello.py``:3435.. click:example::3637 import click3839 @click.command()40 def cli():41 """Prints a greeting."""42 click.echo("Hello, World!")4344Contents of ``pyproject.toml``:4546.. code-block:: toml4748 [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 ]5657 [project.scripts]58 hello = "hello.hello:cli"5960 [build-system]61 requires = ["flit_core<4"]62 build-backend = "flit_core.buildapi"6364The magic is in the ``project.scripts`` section. Each line identifies one executable65script. The first part before the equals sign (``=``) is the name of the script that66should be generated, the second part is the import path followed by a colon67(``:``) with the function to call (the Click command).686970Installation71------------7273When your package is installed, the installer will create an executable script74based on the configuration. During development, you can install in editable75mode using the ``-e`` option. Remember to use a virtual environment!7677.. code-block:: console7879 $ python -m venv .venv80 $ . .venv/bin/activate81 $ pip install -e .8283Afterwards, your command should be available:8485.. click:run::8687 invoke(cli, prog_name="hello")
added:docs/exceptions.md+136 added
1(exception-handling-exit-codes)=23# Exception Handling and Exit Codes45```{eval-rst}6.. currentmodule:: click7```89Click internally uses exceptions to signal various error conditions that10the user of the application might have caused. Primarily this is things11like incorrect usage.1213```{contents}14:depth: 115:local:16```1718## Where are Errors Handled?1920Click's main error handling is happening in {meth}`Command.main`. In21there it handles all subclasses of {exc}`ClickException` as well as the22standard {exc}`EOFError` and {exc}`KeyboardInterrupt` exceptions. The23latter are internally translated into an {exc}`Abort`.2425The logic applied is the following:26271. If an {exc}`EOFError` or {exc}`KeyboardInterrupt` happens, reraise it28 as {exc}`Abort`.292. 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`.323. If an {exc}`Abort` exception is raised print the string ``Aborted!``33 to standard error and exit the program with exit code ``1``.344. If it goes through well, exit the program with exit code ``0``.3536## What if I Don't Want That?3738Generally you always have the option to invoke the {meth}`Command.invoke`39method yourself. For instance if you have a {class}`Command` you can40invoke it manually like this:4142```python43ctx = command.make_context("command-name", ["args", "go", "here"])44with ctx:45 result = command.invoke(ctx)46```4748In this case exceptions will not be handled at all and bubbled up as you49would expect.5051Starting with Click 3.0 you can also use the {meth}`Command.main` method52but disable the standalone mode which will do two things: disable53exception handling and disable the implicit {func}`sys.exit` at the end.5455So you can do something like this:5657```python58command.main(59 ["command-name", "args", "go", "here"],60 standalone_mode=False,61)62```6364## Which Exceptions Exist?6566Click has two exception bases: {exc}`ClickException` which is raised for67all exceptions that Click wants to signal to the user and {exc}`Abort`68which is used to instruct Click to abort the execution.6970A {exc}`ClickException` has a {meth}`ClickException.show` method which71can render an error message to stderr or the given file object. If you72want to use the exception yourself for doing something check the API docs73about what else they provide.7475The following common subclasses exist:7677- {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.8586(help-page-exit-codes)=8788## Help Pages and Exit Codes8990Triggering the a help page intentionally (by passing in ``--help``)91returns exit code 0. If a help page is displayed due to incorrect user92input, the program returns exit code 2. See {ref}`exit-codes` for more93general information.9495For clarity, here is an example.9697```{eval-rst}98.. click:example::99100 @click.group('printer_group')101 def printer_group():102 pass103104 @printer_group.command('printer')105 @click.option('--this')106 def printer(this):107 if this:108 click.echo(this)109110.. click:run::111 invoke(printer_group, args=['--help'])112113The above invocation returns exit code 0.114115.. click:run::116 invoke(printer_group, args=[])117```118119The 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.120121```{eval-rst}122.. click:example::123124 @click.group('printer_group', no_args_is_help=False)125 def printer_group():126 pass127128 @printer_group.command('printer')129 @click.option('--this')130 def printer(this):131 if this:132 click.echo(this)133134.. click:run::135 invoke(printer_group, args=[])136```
deleted:docs/exceptions.rst-126 removed
1.. _exception-handling-exit-codes:23Exception Handling and Exit Codes4==================================56.. currentmodule:: click78Click internally uses exceptions to signal various error conditions that9the user of the application might have caused. Primarily this is things10like incorrect usage.1112.. contents::13 :depth: 114 :local:1516Where are Errors Handled?17-------------------------1819Click's main error handling is happening in :meth:`Command.main`. In20there it handles all subclasses of :exc:`ClickException` as well as the21standard :exc:`EOFError` and :exc:`KeyboardInterrupt` exceptions. The22latter are internally translated into an :exc:`Abort`.2324The logic applied is the following:25261. If an :exc:`EOFError` or :exc:`KeyboardInterrupt` happens, reraise it27 as :exc:`Abort`.282. 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`.313. If an :exc:`Abort` exception is raised print the string ``Aborted!``32 to standard error and exit the program with exit code ``1``.334. If it goes through well, exit the program with exit code ``0``.3435What if I don't want that?36--------------------------3738Generally you always have the option to invoke the :meth:`invoke` method39yourself. For instance if you have a :class:`Command` you can invoke it40manually like this::4142 ctx = command.make_context('command-name', ['args', 'go', 'here'])43 with ctx:44 result = command.invoke(ctx)4546In this case exceptions will not be handled at all and bubbled up as you47would expect.4849Starting with Click 3.0 you can also use the :meth:`Command.main` method50but disable the standalone mode which will do two things: disable51exception handling and disable the implicit :meth:`sys.exit` at the end.5253So you can do something like this::5455 command.main(['command-name', 'args', 'go', 'here'],56 standalone_mode=False)5758Which Exceptions Exist?59-----------------------6061Click has two exception bases: :exc:`ClickException` which is raised for62all exceptions that Click wants to signal to the user and :exc:`Abort`63which is used to instruct Click to abort the execution.6465A :exc:`ClickException` has a :meth:`~ClickException.show` method which66can render an error message to stderr or the given file object. If you67want to use the exception yourself for doing something check the API docs68about what else they provide.6970The following common subclasses exist:7172* :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.808182.. _help-page-exit-codes:8384Help Pages and Exit Codes85--------------------------8687Triggering 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.8889For clarity, here is an example.9091.. click:example::9293 @click.group('printer_group')94 def printer_group():95 pass9697 @printer_group.command('printer')98 @click.option('--this')99 def printer(this):100 if this:101 click.echo(this)102103.. click:run::104 invoke(printer_group, args=['--help'])105106The above invocation returns exit code 0.107108.. click:run::109 invoke(printer_group, args=[])110111The 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.112113.. click:example::114115 @click.group('printer_group', no_args_is_help=False)116 def printer_group():117 pass118119 @printer_group.command('printer')120 @click.option('--this')121 def printer(this):122 if this:123 click.echo(this)124125.. click:run::126 invoke(printer_group, args=[])