Merge branch 'stable' into mark-private-api
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents 790ebd6, 89af4ae · Browse files · 8 files·+658 added−348 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+658 added−348 removed
- tests:+26 added−0 removed
- other:+632 added−348 removed
Provenance
- Commit
a931cfd- Tree
6aa6964- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
790ebd6- Parent 2
89af4ae
8 files changed+658 added−348 removed
added:docs/commands-and-groups.md+372 added
1+# Basic Commands, Groups, Context2+3+```{currentmodule} click4+```5+6+Commands and Groups are the building blocks for Click applications. {class}`Command` wraps a function to make it into a cli command. {class}`Group` wraps Commands and Groups to make them into applications. {class}`Context` is how groups and commands communicate.7+8+```{contents}9+---10+depth: 211+local: true12+---13+```14+15+## Commands16+17+### Basic Command Example18+19+A simple command decorator takes no arguments.20+21+```{eval-rst}22+.. click:example::23+24+ @click.command()25+ @click.option('--count', default=1)26+ def hello(count):27+ for x in range(count):28+ click.echo("Hello!")29+30+.. click:run::31+ invoke(hello, args=['--count', '2',])32+```33+34+### Renaming Commands35+36+By default the command is the function name with underscores replaced by dashes. To change this pass the desired name into the first positional argument.37+38+```{eval-rst}39+.. click:example::40+41+ @click.command('say-hello')42+ @click.option('--count', default=1)43+ def hello(count):44+ for x in range(count):45+ click.echo("Hello!")46+47+.. click:run::48+ invoke(hello, args=['--count', '2',])49+```50+51+### Deprecating Commands52+53+To mark a command as deprecated pass in `deprecated=True`54+55+```{eval-rst}56+.. click:example::57+58+ @click.command('say-hello', deprecated=True)59+ @click.option('--count', default=1)60+ def hello(count):61+ for x in range(count):62+ click.echo("Hello!")63+64+.. click:run::65+ invoke(hello, args=['--count', '2',])66+```67+68+## Groups69+70+### Basic Group Example71+72+A group wraps one or more commands. After being wrapped, the commands are nested under that group. You can see that on the help pages and in the execution. By default, invoking the group with no command shows the help page.73+74+```{eval-rst}75+.. click:example::76+77+ @click.group()78+ def greeting():79+ click.echo('Starting greeting ...')80+81+ @greeting.command('say-hello')82+ @click.option('--count', default=1)83+ def hello(count):84+ for x in range(count):85+ click.echo("Hello!")86+87+At the top level:88+89+.. click:run::90+91+ invoke(greeting)92+93+At the command level:94+95+.. click:run::96+97+ invoke(greeting, args=['say-hello'])98+ invoke(greeting, args=['say-hello', '--help'])99+```100+101+As you can see from the above example, the function wrapped by the group decorator executes unless it is interrupted (for example by calling the help).102+103+### Renaming Groups104+105+To have a name other than the decorated function name as the group name, pass it in as the first positional argument.106+107+```{eval-rst}108+.. click:example::109+110+ @click.group('greet-someone')111+ def greeting():112+ click.echo('Starting greeting ...')113+114+ @greeting.command('say-hello')115+ @click.option('--count', default=1)116+ def hello(count):117+ for x in range(count):118+ click.echo("Hello!")119+120+.. click:run::121+122+ invoke(greeting, args=['say-hello'])123+```124+125+### Group Invocation Without Command126+127+By default, if a group is passed without a command, the group is not invoked and a command automatically passes `--help`. To change this, pass `invoke_without_command=True` to the group. The context object also includes information about whether or not the group invocation would go to a command nested under it.128+129+```{eval-rst}130+.. click:example::131+132+ @click.group(invoke_without_command=True)133+ @click.pass_context134+ def cli(ctx):135+ if ctx.invoked_subcommand is None:136+ click.echo('I was invoked without subcommand')137+ else:138+ click.echo(f"I am about to invoke {ctx.invoked_subcommand}")139+140+ @cli.command()141+ def sync():142+ click.echo('The subcommand')143+144+.. click:run::145+146+ invoke(cli, prog_name='tool', args=[])147+ invoke(cli, prog_name='tool', args=['sync'])148+```149+150+### Group Separation151+152+Command {ref}`parameters` attached to a command belong only to that command.153+154+```{eval-rst}155+.. click:example::156+157+ @click.group()158+ def greeting():159+ pass160+161+ @greeting.command()162+ @click.option('--count', default=1)163+ def hello(count):164+ for x in range(count):165+ click.echo("Hello!")166+167+ @greeting.command()168+ @click.option('--count', default=1)169+ def goodbye(count):170+ for x in range(count):171+ click.echo("Goodbye!")172+173+.. click:run::174+175+ invoke(greeting, args=['hello', '--count', '2'])176+ invoke(greeting, args=['goodbye', '--count', '2'])177+ invoke(greeting)178+```179+180+Additionally parameters for a given group belong only to that group and not to the commands under it. What this means is that options and arguments for a specific command have to be specified *after* the command name itself, but *before* any other command names.181+182+This behavior is observable with the `--help` option. Suppose we have a group called `tool` containing a command called `sub`.183+184+- `tool --help` returns the help for the whole program (listing subcommands).185+- `tool sub --help` returns the help for the `sub` subcommand.186+- But `tool --help sub` treats `--help` as an argument for the main program. Click then invokes the callback for `--help`, which prints the help and aborts the program before click can process the subcommand.187+188+### Arbitrary Nesting189+190+{class}`Commands <Command>` are attached to a {class}`Group`. Multiple groups can be attached to another group. Groups containing multiple groups can be attached to a group, and so on. To invoke a command nested under multiple groups, all the groups under which it is nested must be invoked.191+192+```{eval-rst}193+.. click:example::194+195+ @click.group()196+ def cli():197+ pass198+199+ # Not @click so that the group is registered now.200+ @cli.group()201+ def session():202+ click.echo('Starting session')203+204+ @session.command()205+ def initdb():206+ click.echo('Initialized the database')207+208+ @session.command()209+ def dropdb():210+ click.echo('Dropped the database')211+212+.. click:run::213+214+ invoke(cli, args=['session', 'initdb'])215+```216+217+### Lazily Attaching Commands218+219+Most examples so far have attached the commands to a group immediately, but commands may be registered later. This could be used to split commands into multiple Python modules. Regardless of how they are attached, the commands are invoked identically.220+221+```{eval-rst}222+.. click:example::223+224+ @click.group()225+ def cli():226+ pass227+228+ @cli.command()229+ def initdb():230+ click.echo('Initialized the database')231+232+ @click.command()233+ def dropdb():234+ click.echo('Dropped the database')235+236+ cli.add_command(dropdb)237+238+.. click:run::239+240+ invoke(cli, args=['initdb'])241+ invoke(cli, args=['dropdb'])242+```243+244+## Context Object245+The {class}`Context` object is how commands and groups communicate.246+247+### Auto Envvar Prefix248+249+Automatically built environment variables are supported for options only. To enable this feature, the `auto_envvar_prefix` parameter needs to be passed to the script that is invoked. Each command and parameter is then added as an uppercase underscore-separated variable. If you have a subcommand250+called `run` taking an option called `reload` and the prefix is `WEB`, then the variable is `WEB_RUN_RELOAD`.251+252+Example usage:253+254+```{eval-rst}255+.. click:example::256+257+ @click.command()258+ @click.option('--username')259+ def greet(username):260+ click.echo(f'Hello {username}!')261+262+ if __name__ == '__main__':263+ greet(auto_envvar_prefix='GREETER')264+265+And from the command line:266+267+.. click:run::268+269+ invoke(greet, env={'GREETER_USERNAME': 'john'},270+ auto_envvar_prefix='GREETER')271+```272+273+When using `auto_envvar_prefix` with command groups, the command name274+needs to be included in the environment variable, between the prefix and275+the parameter name, *i.e.* `PREFIX_COMMAND_VARIABLE`. If you have a276+subcommand called `run-server` taking an option called `host` and277+the prefix is `WEB`, then the variable is `WEB_RUN_SERVER_HOST`.278+279+```{eval-rst}280+.. click:example::281+282+ @click.group()283+ @click.option('--debug/--no-debug')284+ def cli(debug):285+ click.echo(f"Debug mode is {'on' if debug else 'off'}")286+287+ @cli.command()288+ @click.option('--username')289+ def greet(username):290+ click.echo(f"Hello {username}!")291+292+ if __name__ == '__main__':293+ cli(auto_envvar_prefix='GREETER')294+295+.. click:run::296+297+ invoke(cli, args=['greet',],298+ env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},299+ auto_envvar_prefix='GREETER')300+```301+302+### Global Context Access303+304+```{versionadded} 5.0305+```306+307+Starting with Click 5.0 it is possible to access the current context from308+anywhere within the same thread through the use of the309+{func}`get_current_context` function which returns it. This is primarily310+useful for accessing the context bound object as well as some flags that311+are stored on it to customize the runtime behavior. For instance the312+{func}`echo` function does this to infer the default value of the `color`313+flag.314+315+Example usage:316+317+```python318+ def get_current_command_name():319+ return click.get_current_context().info_name320+```321+322+It should be noted that this only works within the current thread. If you323+spawn additional threads then those threads will not have the ability to324+refer to the current context. If you want to give another thread the325+ability to refer to this context you need to use the context within the326+thread as a context manager:327+328+```python329+ def spawn_thread(ctx, func):330+ def wrapper():331+ with ctx:332+ func()333+ t = threading.Thread(target=wrapper)334+ t.start()335+ return t336+```337+338+Now the thread function can access the context like the main thread would339+do. However if you do use this for threading you need to be very careful340+as the vast majority of the context is not thread safe! You are only341+allowed to read from the context, but not to perform any modifications on342+it.343+344+345+### Detecting the Source of a Parameter346+347+In some situations it's helpful to understand whether or not an option348+or parameter came from the command line, the environment, the default349+value, or {attr}`Context.default_map`. The350+{meth}`Context.get_parameter_source` method can be used to find this351+out. It will return a member of the {class}`~click.core.ParameterSource`352+enum.353+354+```{eval-rst}355+.. click:example::356+357+ @click.command()358+ @click.argument('port', nargs=1, default=8080, envvar="PORT")359+ @click.pass_context360+ def cli(ctx, port):361+ source = ctx.get_parameter_source("port")362+ click.echo(f"Port came from {source.name}")363+364+.. click:run::365+366+ invoke(cli, prog_name='cli', args=['8080'])367+ println()368+ invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})369+ println()370+ invoke(cli, prog_name='cli', args=[])371+ println()372+```deleted:docs/commands-and-groups.rst-342 removed
1-Basic Commands, Groups, Context2-================================3-4-.. currentmodule:: click5-6-Commands and Groups are the building blocks for Click applications. :class:`Command` wraps a function to make it into a cli command. :class:`Group` wraps Commands and Groups to make them into applications. :class:`Context` is how groups and commands communicate.7-8-.. contents::9- :depth: 210- :local:11-12-Commands13---------------------14-15-Basic Command Example16-^^^^^^^^^^^^^^^^^^^^^^^17-A simple command decorator takes no arguments.18-19-.. click:example::20- @click.command()21- @click.option('--count', default=1)22- def hello(count):23- for x in range(count):24- click.echo("Hello!")25-26-.. click:run::27- invoke(hello, args=['--count', '2',])28-29-Renaming Commands30-^^^^^^^^^^^^^^^^^^^31-By default the command is the function name with underscores replaced by dashes. To change this pass the desired name into the first positional argument.32-33-.. click:example::34- @click.command('say-hello')35- @click.option('--count', default=1)36- def hello(count):37- for x in range(count):38- click.echo("Hello!")39-40-.. click:run::41- invoke(hello, args=['--count', '2',])42-43-Deprecating Commands44-^^^^^^^^^^^^^^^^^^^^^^45-To mark a command as deprecated pass in ``deprecated=True``46-47-.. click:example::48- @click.command('say-hello', deprecated=True)49- @click.option('--count', default=1)50- def hello(count):51- for x in range(count):52- click.echo("Hello!")53-54-.. click:run::55- invoke(hello, args=['--count', '2',])56-57-Groups58-------------59-60-Basic Group Example61-^^^^^^^^^^^^^^^^^^^^^62-A group wraps one or more commands. After being wrapped, the commands are nested under that group. You can see that on the help pages and in the execution. By default, invoking the group with no command shows the help page.63-64-.. click:example::65- @click.group()66- def greeting():67- click.echo('Starting greeting ...')68-69- @greeting.command('say-hello')70- @click.option('--count', default=1)71- def hello(count):72- for x in range(count):73- click.echo("Hello!")74-75-At the top level:76-77-.. click:run::78-79- invoke(greeting)80-81-At the command level:82-83-.. click:run::84-85- invoke(greeting, args=['say-hello'])86- invoke(greeting, args=['say-hello', '--help'])87-88-As you can see from the above example, the function wrapped by the group decorator executes unless it is interrupted (for example by calling the help).89-90-Renaming Groups91-^^^^^^^^^^^^^^^^^92-To have a name other than the decorated function name as the group name, pass it in as the first positional argument.93-94-.. click:example::95- @click.group('greet-someone')96- def greeting():97- click.echo('Starting greeting ...')98-99- @greeting.command('say-hello')100- @click.option('--count', default=1)101- def hello(count):102- for x in range(count):103- click.echo("Hello!")104-105-.. click:run::106-107- invoke(greeting, args=['say-hello'])108-109-Group Invocation Without Command110-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^111-112-By default, if a group is passed without a command, the group is not invoked and a command automatically passes ``--help``. To change this, pass ``invoke_without_command=True`` to the group. The context object also includes information about whether or not the group invocation would go to a command nested under it.113-114-.. click:example::115-116- @click.group(invoke_without_command=True)117- @click.pass_context118- def cli(ctx):119- if ctx.invoked_subcommand is None:120- click.echo('I was invoked without subcommand')121- else:122- click.echo(f"I am about to invoke {ctx.invoked_subcommand}")123-124- @cli.command()125- def sync():126- click.echo('The subcommand')127-128-.. click:run::129-130- invoke(cli, prog_name='tool', args=[])131- invoke(cli, prog_name='tool', args=['sync'])132-133-134-135-Group Separation136-^^^^^^^^^^^^^^^^^^^137-Command :ref:`parameters` attached to a command belong only to that command.138-139-.. click:example::140- @click.group()141- def greeting():142- pass143-144- @greeting.command()145- @click.option('--count', default=1)146- def hello(count):147- for x in range(count):148- click.echo("Hello!")149-150- @greeting.command()151- @click.option('--count', default=1)152- def goodbye(count):153- for x in range(count):154- click.echo("Goodbye!")155-156-.. click:run::157-158- invoke(greeting, args=['hello', '--count', '2'])159- invoke(greeting, args=['goodbye', '--count', '2'])160- invoke(greeting)161-162-Additionally parameters for a given group belong only to that group and not to the commands under it. What this means is that options and arguments for a specific command have to be specified *after* the command name itself, but *before* any other command names.163-164-This behavior is observable with the ``--help`` option. Suppose we have a group called ``tool`` containing a command called ``sub``.165-166-- ``tool --help`` returns the help for the whole program (listing subcommands).167-- ``tool sub --help`` returns the help for the ``sub`` subcommand.168-- But ``tool --help sub`` treats ``--help`` as an argument for the main program. Click then invokes the callback for ``--help``, which prints the help and aborts the program before click can process the subcommand.169-170-Arbitrary Nesting171-^^^^^^^^^^^^^^^^^^^172-:class:`Commands <Command>` are attached to a :class:`Group`. Multiple groups can be attached to another group. Groups containing multiple groups can be attached to a group, and so on. To invoke a command nested under multiple groups, all the groups under which it is nested must be invoked.173-174-.. click:example::175-176- @click.group()177- def cli():178- pass179-180- # Not @click so that the group is registered now.181- @cli.group()182- def session():183- click.echo('Starting session')184-185- @session.command()186- def initdb():187- click.echo('Initialized the database')188-189- @session.command()190- def dropdb():191- click.echo('Dropped the database')192-193-.. click:run::194-195- invoke(cli, args=['session', 'initdb'])196-197-Lazily Attaching Commands198-^^^^^^^^^^^^^^^^^^^^^^^^^^^199-Most examples so far have attached the commands to a group immediately, but commands may be registered later. This could be used to split commands into multiple Python modules. Regardless of how they are attached, the commands are invoked identically.200-201-.. click:example::202-203- @click.group()204- def cli():205- pass206-207- @cli.command()208- def initdb():209- click.echo('Initialized the database')210-211- @click.command()212- def dropdb():213- click.echo('Dropped the database')214-215- cli.add_command(dropdb)216-217-.. click:run::218-219- invoke(cli, args=['initdb'])220- invoke(cli, args=['dropdb'])221-222-Context Object223--------------------224-The :class:`Context` object is how commands and groups communicate.225-226-Auto Envvar Prefix227-^^^^^^^^^^^^^^^^^^^^228-Automatically built environment variables are supported for options only. To enable this feature, the ``auto_envvar_prefix`` parameter needs to be passed to the script that is invoked. Each command and parameter is then added as an uppercase underscore-separated variable. If you have a subcommand229-called ``run`` taking an option called ``reload`` and the prefix is ``WEB``, then the variable is ``WEB_RUN_RELOAD``.230-231-Example usage:232-233-.. click:example::234-235- @click.command()236- @click.option('--username')237- def greet(username):238- click.echo(f'Hello {username}!')239-240- if __name__ == '__main__':241- greet(auto_envvar_prefix='GREETER')242-243-And from the command line:244-245-.. click:run::246-247- invoke(greet, env={'GREETER_USERNAME': 'john'},248- auto_envvar_prefix='GREETER')249-250-When using ``auto_envvar_prefix`` with command groups, the command name251-needs to be included in the environment variable, between the prefix and252-the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a253-subcommand called ``run-server`` taking an option called ``host`` and254-the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``.255-256-.. click:example::257-258- @click.group()259- @click.option('--debug/--no-debug')260- def cli(debug):261- click.echo(f"Debug mode is {'on' if debug else 'off'}")262-263- @cli.command()264- @click.option('--username')265- def greet(username):266- click.echo(f"Hello {username}!")267-268- if __name__ == '__main__':269- cli(auto_envvar_prefix='GREETER')270-271-.. click:run::272-273- invoke(cli, args=['greet',],274- env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},275- auto_envvar_prefix='GREETER')276-277-Global Context Access278-^^^^^^^^^^^^^^^^^^^^^^279-280-.. versionadded:: 5.0281-282-Starting with Click 5.0 it is possible to access the current context from283-anywhere within the same thread through the use of the284-:func:`get_current_context` function which returns it. This is primarily285-useful for accessing the context bound object as well as some flags that286-are stored on it to customize the runtime behavior. For instance the287-:func:`echo` function does this to infer the default value of the `color`288-flag.289-290-Example usage::291-292- def get_current_command_name():293- return click.get_current_context().info_name294-295-It should be noted that this only works within the current thread. If you296-spawn additional threads then those threads will not have the ability to297-refer to the current context. If you want to give another thread the298-ability to refer to this context you need to use the context within the299-thread as a context manager::300-301- def spawn_thread(ctx, func):302- def wrapper():303- with ctx:304- func()305- t = threading.Thread(target=wrapper)306- t.start()307- return t308-309-Now the thread function can access the context like the main thread would310-do. However if you do use this for threading you need to be very careful311-as the vast majority of the context is not thread safe! You are only312-allowed to read from the context, but not to perform any modifications on313-it.314-315-316-Detecting the Source of a Parameter317-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^318-319-In some situations it's helpful to understand whether or not an option320-or parameter came from the command line, the environment, the default321-value, or :attr:`Context.default_map`. The322-:meth:`Context.get_parameter_source` method can be used to find this323-out. It will return a member of the :class:`~click.core.ParameterSource`324-enum.325-326-.. click:example::327-328- @click.command()329- @click.argument('port', nargs=1, default=8080, envvar="PORT")330- @click.pass_context331- def cli(ctx, port):332- source = ctx.get_parameter_source("port")333- click.echo(f"Port came from {source.name}")334-335-.. click:run::336-337- invoke(cli, prog_name='cli', args=['8080'])338- println()339- invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})340- println()341- invoke(cli, prog_name='cli', args=[])342- println()modified:docs/index.rst+1 added
77 unmodified lines78 :maxdepth: 179 80 entry-points81 setuptools82+ standalone-apps83 upgrade-guides84 support-multiple-versions85 86 Conceptual Guides59 unmodified linesadded:docs/standalone-apps.md+148 added
1+# Standalone Application with Briefcase2+3+[Briefcase](https://briefcase.beeware.org/) is a tool for packaging Python4+projects as standalone native applications. It can produce installers and5+executables for macOS, Windows, and Linux that do not require the user to6+install Python or any dependencies.7+8+- Produces platform-native installers (``.pkg`` on macOS, ``.msi`` on9+ Windows, ``.deb``/``.rpm`` on Linux).10+- Bundles a Python interpreter and all dependencies.11+- Supports passing command line arguments to the app.12+13+This page outlines the basics of packaging a Click application with14+Briefcase. Be sure to read its15+[documentation](https://briefcase.beeware.org/en/stable/how-to/building/cli-apps/)16+and use ``briefcase --help`` to understand what features are available.17+18+## Installation19+20+Install Briefcase in the virtual environment:21+22+```console23+pip install briefcase24+```25+26+## Configuration27+28+Add a ``[tool.briefcase]`` section and a29+``[tool.briefcase.app.<app-name>]`` section to ``pyproject.toml``.30+Set ``console_app = true`` so Briefcase treats the project as a command31+line application rather than a GUI application.32+33+Given a Click application with the following project structure:34+35+```text36+hello-cli/37+ src/38+ hello_cli/39+ __init__.py40+ app.py41+ LICENSE42+ pyproject.toml43+```44+45+Where ``app.py`` contains a Click command:46+47+```python48+import click49+50+@click.command()51+@click.argument("name", default="World")52+@click.option("--count", default=1, help="Number of times to greet.")53+def main(name, count):54+ """Greet someone by NAME (default: World)."""55+ for _ in range(count):56+ click.echo(f"Hello, {name}!")57+```58+59+Add the following Briefcase configuration to ``pyproject.toml``:60+61+```toml62+[tool.briefcase]63+project_name = "Hello CLI"64+bundle = "com.example"65+version = "0.0.1"66+url = "https://example.com/hello-cli"67+license.file = "LICENSE"68+author = "Your Name"69+author_email = "you@example.com"70+71+[tool.briefcase.app.hello-cli]72+formal_name = "Hello CLI"73+description = "My first application"74+long_description = """More details about the app should go here.75+"""76+sources = [77+ "src/hello_cli",78+]79+console_app = true80+requires = [81+ "click",82+]83+```84+85+The key settings are:86+87+- ``console_app = true`` -- tells Briefcase this is a terminal88+ application, not a GUI.89+- ``sources`` -- the list of source packages to include.90+- ``requires`` -- the Python dependencies to bundle (Click and any other91+ libraries the project needs).92+93+## Entry Point94+95+Briefcase launches the application by running the package with96+``python -m <package>``, so a ``__main__.py`` file **must** exist in the97+package. Without it, Briefcase will not be able to start the application.98+99+Create ``__main__.py`` in the package directory and call the Click100+command:101+102+```python103+from hello_cli.app import main104+105+if __name__ == "__main__":106+ main()107+```108+109+## Running110+111+Use ``briefcase dev`` to run the application directly from the source112+tree. Pass command line arguments after ``--``:113+114+```console115+$ briefcase dev -- World116+Hello, World!117+$ briefcase dev -- World --count 2118+Hello, World!119+Hello, World!120+```121+122+## Building and Packaging123+124+To create a distributable executable, run the following commands:125+126+```console127+briefcase create128+briefcase build129+briefcase package130+```131+132+``briefcase create`` downloads a Python interpreter and installs133+dependencies into an isolated app bundle. ``briefcase build`` compiles134+the app, and ``briefcase package`` produces the final platform installer.135+136+On macOS, this produces a ``.pkg`` installer. On Windows, it produces a137+``.msi`` installer. On Linux, it produces a system package (``.deb``,138+``.rpm``, etc.) for the current distribution.139+140+Once installed, users can run the application directly from the terminal:141+142+```console143+$ hello-cli World144+Hello, World!145+$ hello-cli World --count 2146+Hello, World!147+Hello, World!148+```modified:docs/testing.md+48 added
194 unmodified lines195 196 Prompts will be emulated so they write the input data to197 the output stream as well. If hidden input is expected then this198 does not happen.199+200+## File Descriptors and Low-Level I/O201+202+{class}`CliRunner` captures output by replacing203+`sys.stdout` and `sys.stderr` with in-memory204+{class}`~io.BytesIO`-backed wrappers. This is205+Python-level redirection: calls to {func}`~click.echo`,206+{func}`print`, or `sys.stdout.write()` are captured, but207+the wrappers have no OS-level file descriptor.208+209+Code that calls `fileno()` on `sys.stdout` or210+`sys.stderr`, like {mod}`faulthandler`,211+{mod}`subprocess`, or C extensions, would normally crash212+with {exc}`io.UnsupportedOperation` inside213+{class}`CliRunner`.214+215+To avoid this, {class}`CliRunner` preserves the original216+stream's file descriptor and exposes it via `fileno()` on217+the replacement wrapper.218+219+This means:220+- **Python-level writes** (`print()`, `click.echo()`,221+ ...) are captured as usual.222+- **fd-level writes** (C code writing directly to the223+ file descriptor) go to the original terminal and are224+ **not** captured.225+226+This is the same trade-off that227+[pytest](https://docs.pytest.org/en/stable/how-to/capture-stdout-stderr.html)228+makes with its two capture modes:229+230+- `capsys`, which captures Python-level output, where231+ `fileno()` raises `UnsupportedOperation` and fd-level232+ writes are not captured.233+- `capfd`, which captures fd-level output via234+ `os.dup2()`, where `fileno()` works and fd-level235+ writes *are* captured.236+237+Rather than implementing a full `capfd`-style mechanism,238+{class}`CliRunner` takes the simpler path: expose the239+original `fd` so that standard library helpers keep240+working, while accepting that their output is not241+captured.242+243+```{versionchanged} 8.3.3244+`fileno()` on the redirected streams now returns the245+original stream's file descriptor instead of raising.246+```modified:src/click/testing.py+59 added-6 removed
99 unmodified lines100 self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)101 102 103 class _NamedTextIOWrapper(io.TextIOWrapper):104+ """A :class:`~io.TextIOWrapper` with custom ``name`` and ``mode``105+ that does not close its underlying buffer.106+107+ An optional ``original_fd`` preserves the file descriptor of the108+ stream being replaced, so that C-level consumers that call109+ :meth:`fileno` (``faulthandler``, ``subprocess``, ...) still work.110+ Inspired by pytest's ``capsys``/``capfd`` split: see :doc:`/testing`111+ for details.112+113+ .. versionchanged:: 8.3.3114+ Added ``original_fd`` parameter and :meth:`fileno` override.115+ """116+117 def __init__(105- self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any118+ self,119+ buffer: t.BinaryIO,120+ name: str,121+ mode: str,122+ *,123+ original_fd: int = -1,124+ **kwargs: t.Any,125 ) -> None:126 super().__init__(buffer, **kwargs)127 self._name = name128 self._mode = mode129+ self._original_fd = original_fd130 131 def close(self) -> None:112- """113- The buffer this object contains belongs to some other object, so114- prevent the default __del__ implementation from closing that buffer.132+ """The buffer this object contains belongs to some other object,133+ so prevent the default ``__del__`` implementation from closing134+ that buffer.135 136 .. versionadded:: 8.3.2137 """118- ...138 139+ def fileno(self) -> int:140+ """Return the file descriptor of the original stream, if one was141+ provided at construction time.142+143+ This allows C-level consumers (``faulthandler``, ``subprocess``,144+ signal handlers, ...) to obtain a valid fd without crashing, even145+ though the Python-level writes are redirected to an in-memory146+ buffer.147+148+ .. versionadded:: 8.3.3149+ """150+ if self._original_fd >= 0:151+ return self._original_fd152+ return super().fileno()153+154 @property155 def name(self) -> str:156 return self._name157 196 unmodified lines354 env = self.make_env(env)355 356 stream_mixer = StreamMixer()357 358+ # Preserve the original file descriptors so that C-level359+ # consumers (faulthandler, subprocess, etc.) can still obtain a360+ # valid fd from the redirected streams. The original streams361+ # may themselves lack a fileno() (e.g. when CliRunner is used362+ # inside pytest's capsys), so we fall back to -1.363+ def _safe_fileno(stream: t.IO[t.Any]) -> int:364+ try:365+ return stream.fileno()366+ except (AttributeError, io.UnsupportedOperation):367+ return -1368+369+ old_stdout_fd = _safe_fileno(old_stdout)370+ old_stderr_fd = _safe_fileno(old_stderr)371+372 if self.echo_stdin:373 bytes_input = echo_input = t.cast(374 t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout)375 )7 unmodified lines383 # large chunk which is echoed early.384 text_input._CHUNK_SIZE = 1 # type: ignore385 386 sys.stdout = _NamedTextIOWrapper(339- stream_mixer.stdout, encoding=self.charset, name="<stdout>", mode="w"387+ stream_mixer.stdout,388+ encoding=self.charset,389+ name="<stdout>",390+ mode="w",391+ original_fd=old_stdout_fd,392 )393 394 sys.stderr = _NamedTextIOWrapper(395 stream_mixer.stderr,396 encoding=self.charset,397 name="<stderr>",398 mode="w",399 errors="backslashreplace",400+ original_fd=old_stderr_fd,401 )402 403 @_pause_echo(echo_input) # type: ignore404 def visible_input(prompt: str | None = None) -> str:268 unmodified linesmodified:tests/test_testing.py+26 added
1+import faulthandler2 import os3 import pdb4 import sys5 from io import BytesIO513 unmodified lines519 runner = CliRunner()520 runner.invoke(cli)521 522 assert pdb.Pdb.__init__ is original523+524+525+def test_faulthandler_enable(runner):526+ """``faulthandler.enable()`` inside ``CliRunner`` should not crash with527+ ``io.UnsupportedOperation: fileno``.528+529+ ``faulthandler.enable()`` needs a real OS file descriptor to register530+ its signal handler. ``CliRunner`` replaces ``sys.stderr`` with a531+ ``BytesIO`` wrapper that has no ``fileno()``, causing the call to fail.532+533+ Reproduce:https://github.com/pallets/click/issues/2865534+ """535+536+ @click.command()537+ @click.option("--flag", type=bool, default=True)538+ def cli(flag):539+ click.echo("Executing main function...")540+ if flag:541+ click.echo("Registering faulthandler")542+ faulthandler.enable()543+ click.echo("Finished executing main function.")544+545+ result = runner.invoke(cli, ["--flag", True])546+ assert result.exit_code == 0, result.output547+ assert "Finished executing main function." in result.outputmodified:CHANGES.rst+4 added
20 unmodified lines21 ``pytest-xdist`` to detect test pollution and race conditions. :pr:`3151`22 - Add contributor documentation for running stress tests, randomized23 parallel tests, and Flask smoke tests. :pr:`3151` :pr:`3177`24 - Mark ``make_default_short_help`` as private API. :issue:`3189` :pr:`3250`25+- ``CliRunner``'s redirected streams now expose the original file descriptor26+ via ``fileno()``, so that ``faulthandler``, ``subprocess``, and other27+ C-level consumers no longer crash with ``io.UnsupportedOperation``.28+ :issue:`2865`29 30 Version 8.3.231 -------------32 1323 unmodified lines