### Install Click using pip Source: https://github.com/python-trio/asyncclick/blob/main/docs/quickstart.md This command installs the Click library from the Python Package Index (PyPI). It is recommended to install within a virtual environment for better dependency management. ```console pip install click ``` -------------------------------- ### Adding Options and Arguments with asyncclick Source: https://github.com/python-trio/asyncclick/blob/main/docs/quickstart.md Illustrates how to add parameters to commands using the `click.option()` and `click.argument()` decorators. These decorators define user-configurable inputs for your command-line tools. ```python import click @click.command() @click.option('--count', default=1, help='number of greetings') @click.argument('name') def hello(count, name): for x in range(count): click.echo(f"Hello {name}!") ``` -------------------------------- ### Registering Commands Later with asyncclick Source: https://github.com/python-trio/asyncclick/blob/main/docs/quickstart.md Demonstrates how to register commands with a group after their definition using `group.add_command()`. This is useful for organizing commands across multiple modules. ```python import click @click.command() def greet(): click.echo("Hello, World!") @click.group() def group(): pass group.add_command(greet) ``` -------------------------------- ### AsyncClick Example: Generating Help Page Source: https://github.com/python-trio/asyncclick/blob/main/docs/index.rst Shows how to generate the help page for an AsyncClick command programmatically. This is useful for testing the help output or for debugging. ```python from asyncclick.testing import CliRunner # Assuming 'hello' is your asyncclick command function defined elsewhere # from your_module import hello # Example usage: runner = CliRunner() result = runner.invoke(hello, ['--help'], prog_name='python hello.py') print(result.output) ``` -------------------------------- ### Click CLI Example: Help and Execution Source: https://github.com/python-trio/asyncclick/blob/main/docs/advanced.rst This example showcases the usage of `click.testing.CliRunner` to invoke a Click CLI application with different arguments. It demonstrates how to simulate `--help` requests and execute commands with specific options and code snippets for timing. The `invoke` function from `click.testing` is a key component. ```python invoke(cli, prog_name='cli', args=['--help']) println() invoke(cli, prog_name='cli', args=['-n', '100', 'a = 1; b = 2; a * b']) println() invoke(cli, prog_name='cli', args=['-v', 'a = 1; b = 2; a * b']) ``` -------------------------------- ### AsyncClick Example: Running a Command Source: https://github.com/python-trio/asyncclick/blob/main/docs/index.rst Demonstrates how to programmatically invoke an AsyncClick command with specific arguments and input. This is useful for testing or integrating CLI logic within other Python scripts. ```python from asyncclick.testing import CliRunner # Assuming 'hello' is your asyncclick command function defined elsewhere # from your_module import hello # Example usage: runner = CliRunner() result = runner.invoke(hello, ['--count=3'], prog_name='python hello.py', input='John\n') print(result.output) ``` -------------------------------- ### Install Package in Editable Mode Source: https://github.com/python-trio/asyncclick/blob/main/docs/entry-points.rst This console command sequence demonstrates how to set up a Python virtual environment and install a local package in editable mode using pip. This is useful for development, allowing changes to the code to be reflected immediately without reinstallation. ```console python -m venv .venv . .venv/bin/activate pip install -e . ``` -------------------------------- ### Get Parameter Source in Asyncclick Source: https://github.com/python-trio/asyncclick/blob/main/docs/commands-and-groups.rst This example demonstrates how to retrieve the source of a command-line parameter using `ctx.get_parameter_source`. It shows how the 'port' parameter can originate from the command line, environment variables, or a default value. The `click.core.ParameterSource` enum is used to identify the origin. ```python import click from click.testing import CliRunner @click.command() @click.argument('port', nargs=1, default=8080, envvar="PORT") @click.pass_context def cli(ctx, port): source = ctx.get_parameter_source("port") click.echo(f"Port came from {source.name}") runner = CliRunner() # Example 1: Port from command line result1 = runner.invoke(cli, prog_name='cli', args=['8080']) print(result1.output.strip()) # Example 2: Port from environment variable result2 = runner.invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"}) print(result2.output.strip()) # Example 3: Port from default value result3 = runner.invoke(cli, prog_name='cli', args=[]) print(result3.output.strip()) ``` -------------------------------- ### Create a basic Click command Source: https://github.com/python-trio/asyncclick/blob/main/docs/quickstart.md Demonstrates how to create a simple command-line application using Click. The `@click.command()` decorator transforms a Python function into a callable command. The `click.echo()` function is used for output, offering robustness and style support. ```python import click @click.command() def hello(): click.echo('Hello World!') if __name__ == '__main__': hello() ``` -------------------------------- ### Async Command Groups and Subcommands in Python Source: https://context7.com/python-trio/asyncclick/llms.txt Illustrates how to create command groups using `@click.group()` and register subcommands using `@group.command()`. This example shows how to pass context objects and handle different command functionalities. Requires `asyncclick`. ```python import asyncclick as click @click.group() @click.option("--debug/--no-debug", default=False, help="Enable debug mode.") @click.pass_context def cli(ctx, debug): """A CLI application with multiple commands.""" ctx.ensure_object(dict) ctx.obj["DEBUG"] = debug @cli.command() @click.argument("name") @click.pass_context async def greet(ctx, name): """Greet a user by name.""" if ctx.obj["DEBUG"]: click.echo(f"Debug mode is on") click.echo(f"Hello, {name}!") @cli.command() @click.option("--count", default=1, type=int, help="Number of items.") async def count(count): """Count up to a number.""" for i in range(1, count + 1): click.echo(f"Count: {i}") if __name__ == "__main__": cli() ``` -------------------------------- ### Invoke a Click command with context settings Source: https://github.com/python-trio/asyncclick/blob/main/docs/testing.md Illustrates how to pass additional keyword arguments to CliRunner.invoke to configure the initial Context object. This example sets a fixed terminal width for testing. ```python import click @click.group() def cli(): pass @cli.command() def sync(): click.echo('Syncing') ``` ```python from click.testing import CliRunner from sync import cli def test_sync(): runner = CliRunner() result = runner.invoke(cli, ['sync'], terminal_width=60) assert result.exit_code == 0 assert 'Debug mode is on' in result.output assert 'Syncing' in result.output ``` -------------------------------- ### Asyncclick Example: Greeting Command Source: https://github.com/python-trio/asyncclick/blob/main/README.md A simple asynchronous command-line interface using asyncclick that greets a user a specified number of times. It demonstrates the use of async commands, options, prompts, and asynchronous sleeping within the command handler. Dependencies include asyncclick and anyio. ```python import asyncclick as click import anyio @click.command() @click.option("--count", default=1, help="Number of greetings.") @click.option("--name", prompt="Your name", help="The person to greet.") async def hello(count, name): """Simple program that greets NAME for a total of COUNT times.""" for _ in range(count): click.echo(f"Hello, {name}!") await anyio.sleep(0.2) if __name__ == '__main__': hello() # alternately: anyio.run(hello.main) ``` -------------------------------- ### IntRange and FloatRange Type Examples - Python Source: https://github.com/python-trio/asyncclick/blob/main/docs/parameter-types.rst Illustrates the use of click.IntRange and click.FloatRange for validating numeric input within specified bounds. The example shows how to set minimum and maximum values, enable clamping, and handle out-of-range inputs. ```python @click.command() @click.option("--count", type=click.IntRange(0, 20, clamp=True)) @click.option("--digit", type=click.IntRange(0, 9)) def repeat(count, digit): click.echo(str(digit) * count) ``` -------------------------------- ### Create nested Click commands (Group and Commands) Source: https://github.com/python-trio/asyncclick/blob/main/docs/quickstart.md Illustrates how to create a command-line interface with nested commands using `click.group` and `click.command`. The `cli.add_command()` method is used to attach subcommands to a group. This structure allows for organizing complex CLIs. ```python @click.group() def cli(): pass @click.command() def initdb(): click.echo('Initialized the database') @click.command() def dropdb(): click.echo('Dropped the database') cli.add_command(initdb) cli.add_command(dropdb) if __name__ == '__main__': cli() ``` -------------------------------- ### Create nested Click commands (Group with command decorator) Source: https://github.com/python-trio/asyncclick/blob/main/docs/quickstart.md An alternative method for creating nested commands in Click, using the `@cli.command()` decorator directly on subcommands. This approach simplifies the code by automatically adding commands to the group. ```python @click.group() def cli(): pass @cli.command() def initdb(): click.echo('Initialized the database') @cli.command() def dropdb(): click.echo('Dropped the database') if __name__ == '__main__': cli() ``` -------------------------------- ### Nested Commands and Groups in Click Source: https://github.com/python-trio/asyncclick/blob/main/docs/commands-and-groups.rst Demonstrates how to create nested commands and groups in Click. This allows for structuring command-line interfaces with subcommands and hierarchical organization. The example shows how to define a group and attach commands to it, and how to invoke the nested commands. ```python import click @click.group() def cli(): pass # Not @click so that the group is registered now. @cli.group() def session(): click.echo('Starting session') @session.command() def initdb(): click.echo('Initialized the database') @session.command() def dropdb(): click.echo('Dropped the database') ``` -------------------------------- ### Show Default Values in Python Source: https://github.com/python-trio/asyncclick/blob/main/docs/prompts.md This Python code snippet extends the previous example by including the `show_default` parameter. This parameter allows the user to see what the default value will be when the help message is displayed. This improves the user experience by providing more context about the option's behavior. ```python import os @click.command() @click.option( "--username", prompt=True, default=lambda: os.environ.get("USER", ""), show_default="current user" ) def hello(username): click.echo(f"Hello, {username}!") ``` -------------------------------- ### Lazily Attaching Commands in Click Source: https://github.com/python-trio/asyncclick/blob/main/docs/commands-and-groups.rst Illustrates how to register commands to a group after the group has been defined. This approach allows for splitting commands into multiple Python modules. The example shows how to define a group and then add commands to it using `cli.add_command()`. ```python import click @click.group() def cli(): pass @cli.command() def initdb(): click.echo('Initialized the database') @click.command() def dropdb(): click.echo('Dropped the database') cli.add_command(dropdb) ``` -------------------------------- ### Async Arguments Handling in Python Source: https://context7.com/python-trio/asyncclick/llms.txt Demonstrates how to define positional arguments using `@click.argument()` in AsyncClick. This example includes handling a variable number of arguments using `nargs=-1` and specifying argument types like `click.Path`. Requires `asyncclick`. ```python import asyncclick as click @click.command() @click.argument("src", type=click.Path(exists=True)) @click.argument("dest", type=click.Path()) @click.argument("files", nargs=-1, type=click.Path()) async def copy(src, dest, files): """Copy SRC to DEST, optionally with additional FILES. \b Examples: copy source.txt destination.txt copy /src /dest file1.txt file2.txt file3.txt """ click.echo(f"Copying {src} to {dest}") if files: click.echo(f"Additional files: {', '.join(files)}") if __name__ == "__main__": copy() ``` -------------------------------- ### Multi-Value Option with nargs (Python) Source: https://github.com/python-trio/asyncclick/blob/main/docs/options.md Demonstrates how to configure an option to accept multiple values using the 'nargs' parameter. The values are passed to the function as a tuple. This example expects two float values for the '--pos' option. ```python @click.command() @click.option('--pos', nargs=2, type=float) def findme(pos): a, b = pos click.echo(f"{a} / {b}") ``` -------------------------------- ### Define and Echo String Option (Python) Source: https://github.com/python-trio/asyncclick/blob/main/docs/options.md Demonstrates defining a Click option '--string-to-echo' and using it to echo the provided string. This example shows how Click infers the function argument name when it follows a specific naming convention. ```python @click.command() @click.option('--string-to-echo', 'string_to_echo') def echo(string_to_echo): click.echo(string_to_echo) ``` -------------------------------- ### Auto Environment Variable Prefix in Click Source: https://github.com/python-trio/asyncclick/blob/main/docs/commands-and-groups.rst Explains how to use the `auto_envvar_prefix` feature in Click to automatically build environment variables for options. This allows users to configure command-line options using environment variables. The example demonstrates how to define a command with options and how to set environment variables to override the default values. ```python import click @click.command() @click.option('--username') def greet(username): click.echo(f'Hello {username}!') if __name__ == '__main__': greet(auto_envvar_prefix='GREETER') ``` ```python import click @click.group() @click.option('--debug/--no-debug') def cli(debug): click.echo(f"Debug mode is {'on' if debug else 'off'}") @cli.command() @click.option('--username') def greet(username): click.echo(f"Hello {username}!") if __name__ == '__main__': cli(auto_envvar_prefix='GREETER') ``` -------------------------------- ### Asyncclick Optional Option with Flag Value Source: https://github.com/python-trio/asyncclick/blob/main/docs/options.md This example shows how to define an option in Asyncclick that can accept an optional value. If the option flag is provided without a value, it defaults to the `flag_value` specified. The `default` parameter is used when no flag or value is provided at all. This functionality is useful for creating flexible command-line interfaces. ```python import click from click.testing import CliRunner runner = CliRunner() @click.command() @click.option("--name", is_flag=False, flag_value="Flag", default="Default") def hello(name): click.echo(f"Hello, {name}!") # Example usage: result_no_args = runner.invoke(hello, args=[]) print(f"Result with no args: {result_no_args.output.strip()}") result_with_value = runner.invoke(hello, args=["--name", "Value"]) print(f"Result with value: {result_with_value.output.strip()}") result_with_flag = runner.invoke(hello, args=["--name"]) print(f"Result with flag: {result_with_flag.output.strip()}") ``` -------------------------------- ### Deferred Import Logic in Click Command Callback Source: https://github.com/python-trio/asyncclick/blob/main/docs/complex.rst This Python example shows how to defer the actual import of a function (`foo_concrete`) until the command is invoked. The Click command definition itself remains unaware of this deferred import, allowing standard Click utilities to function correctly. ```python @click.command() @click.option("-n", type=int) @click.option("-w", type=str) def foo(n, w): from mylibrary import foo_concrete foo_concrete(n, w) ``` -------------------------------- ### Accessing Current Context in Click Source: https://github.com/python-trio/asyncclick/blob/main/docs/commands-and-groups.rst Demonstrates how to access the current context from anywhere within the same thread using `get_current_context()`. This is useful for accessing the context bound object and flags to customize runtime behavior. The example shows how to get the current command name. ```python import click def get_current_command_name(): return click.get_current_context().info_name ``` -------------------------------- ### Override Value Completion with Python Function Source: https://github.com/python-trio/asyncclick/blob/main/docs/shell-completion.md Customizes value completions for a parameter without a custom type by providing a `shell_complete` function. This function receives the context, parameter, and incomplete input, returning a list of `CompletionItem` objects or strings. The example suggests environment variables starting with the incomplete value. ```python import os import click def complete_env_vars(ctx, param, incomplete): return [k for k in os.environ if k.startswith(incomplete)] @click.command() @click.argument("name", shell_complete=complete_env_vars) def cli(name): click.echo(f"Name: {name}") click.echo(f"Value: {os.environ[name]}") ``` -------------------------------- ### Define Main CLI with Lazy Subcommands in Python Source: https://github.com/python-trio/asyncclick/blob/main/docs/complex.rst This Python code defines the main CLI entry point using asyncclick's `LazyGroup`. It specifies subcommands 'foo' and 'bar' to be loaded lazily from their respective modules ('foo.cli', 'bar.cli'). This setup allows the main CLI to start without importing all subcommand logic immediately. ```python import asyncclick as click from lazy_group import LazyGroup @click.group( cls=LazyGroup, lazy_subcommands={"foo": "foo.cli", "bar": "bar.cli"}, help="main CLI command for lazy example", ) def cli(): pass ``` -------------------------------- ### GET /version_option Source: https://github.com/python-trio/asyncclick/blob/main/docs/option-decorators.rst The version_option decorator adds a --version option to a command-line interface, which prints the version number and exits the program. ```APIDOC ## GET /version_option ### Description This endpoint demonstrates the use of the version_option decorator to display the program's version. ### Method GET ### Endpoint /version_option --version ### Parameters #### Query Parameters - **version** (boolean) - Optional - If true, displays the version. ### Request Example { "version": true } ### Response #### Success Response (200) - **version** (string) - The program's version number. #### Response Example { "version": "1.0.0" } ``` -------------------------------- ### Intelligent File Opening with Click Source: https://github.com/python-trio/asyncclick/blob/main/docs/utils.md Demonstrates how to use `click.open_file` to intelligently open standard input/output streams or regular files. It supports context management to ensure proper file handling, especially for standard streams. ```python import click stdout = click.open_file('-', 'w') test_file = click.open_file('test.txt', 'w') with click.open_file(filename, 'w') as f: f.write('Hello World!\n') ``` -------------------------------- ### Basic Command Creation with Click Source: https://github.com/python-trio/asyncclick/blob/main/docs/commands-and-groups.rst Demonstrates how to create a simple command-line interface command using the @click.command() decorator. This command accepts an optional --count option and echoes 'Hello!' a specified number of times. It requires the 'click' library. ```python import click @click.command() @click.option('--count', default=1) def hello(count): for x in range(count): click.echo("Hello!") # Example of how to invoke this command (for testing/demonstration): # from click.testing import CliRunner # runner = CliRunner() # result = runner.invoke(hello, args=['--count', '2']) # print(result.output) ``` -------------------------------- ### Configure Project with Entry Points in pyproject.toml Source: https://github.com/python-trio/asyncclick/blob/main/docs/entry-points.rst This TOML configuration file defines a Python project's metadata and build system. The `[project.scripts]` section is crucial for defining command-line entry points, mapping script names to Python functions. It requires Python 3.11+ and the 'click' library. ```toml [project] name = "hello" version = "1.0.0" description = "Hello CLI" requires-python = ">=3.11" dependencies = [ "click>=8.1", ] [project.scripts] hello = "hello.hello:cli" [build-system] requires = ["flit_core<4"] build-backend = "flit_core.buildapi" ``` -------------------------------- ### Basic Option Definition (Python) Source: https://github.com/python-trio/asyncclick/blob/main/docs/options.md A fundamental example of defining a Click option '--text'. This option accepts a string value and echoes it. If no value is provided, the function argument will be None. ```python @click.command() @click.option('--text') def print_this(text): click.echo(text) ``` -------------------------------- ### Group Callback Invocation Example Source: https://github.com/python-trio/asyncclick/blob/main/docs/commands.rst Demonstrates how a group's callback is executed when a subcommand is invoked. The callback receives options like 'debug' which are not passed to the subcommand. ```python import click @click.group() @click.option('--debug/--no-debug', default=False) def cli(debug): click.echo(f"Debug mode is {'on' if debug else 'off'}") @cli.command() def sync(): click.echo('Syncing') # Example of how to run this: # from click.testing import CliRunner # runner = CliRunner() # result = runner.invoke(cli, prog_name='tool.py') # print(result.output) # result = runner.invoke(cli, prog_name='tool.py', args=['--debug', 'sync']) # print(result.output) ``` -------------------------------- ### File Handling with Asyncclick Source: https://context7.com/python-trio/asyncclick/llms.txt Demonstrates how to use `click.File` for automatic file handling, including support for stdin/stdout via '-'. It shows reading from an input file and writing to an output file, as well as handling binary data. ```python import asyncclick as click @click.command() @click.argument("input", type=click.File("r")) @click.argument("output", type=click.File("w")) async def process(input, output): """Process INPUT file and write to OUTPUT. Use '-' for stdin/stdout. """ content = input.read() processed = content.upper() output.write(processed) click.echo("Processing complete!", err=True) @click.command() @click.option( "--input", "-i", type=click.File("rb"), default="-", help="Input file (default: stdin)." ) @click.option( "--output", "-o", type=click.File("wb"), default="-", help="Output file (default: stdout)." ) async def convert(input, output): """Convert binary data between formats.""" data = input.read() output.write(data) if __name__ == "__main__": process() ``` -------------------------------- ### Get CLI Structure Information Source: https://github.com/python-trio/asyncclick/blob/main/CHANGES.rst Retrieve a dictionary representing the structure of an entire CLI application. This is useful for generating user-facing documentation or analyzing the CLI's components. ```python from asyncclick.testing import Context # Assuming 'cli' is your asyncclick command group or command cli_info = Context(cli).to_info_dict() ``` -------------------------------- ### Basic Async Command with Options in Python Source: https://context7.com/python-trio/asyncclick/llms.txt Demonstrates creating a basic asynchronous command using `@click.command()` and adding options with `@click.option()`. It includes a simple asynchronous sleep operation within the command handler. Requires `asyncclick` and `anyio`. ```python import asyncclick as click import anyio @click.command() @click.option("--count", default=1, help="Number of greetings.") @click.option("--name", prompt="Your name", help="The person to greet.") async def hello(count, name): """Simple program that greets NAME for a total of COUNT times.""" for _ in range(count): click.echo(f"Hello, {name}!") await anyio.sleep(0.1) if __name__ == "__main__": hello() ``` -------------------------------- ### Async Prompts with AsyncClick Source: https://context7.com/python-trio/asyncclick/llms.txt Demonstrates the use of asynchronous prompts in AsyncClick, which are compatible with asyncio, trio, or anyio. This snippet shows basic prompts, prompts with defaults, type conversion, hidden input for passwords with confirmation, and confirmation prompts. It requires the `asyncclick` and `anyio` libraries. ```python import asyncclick as click import anyio @click.command() async def interactive(): """Interactive command with async prompts.""" # Basic async prompt name = await click.prompt("What's your name?") click.echo(f"Hello, {name}!") # Prompt with default color = await click.prompt("Favorite color", default="blue") click.echo(f"Your favorite color is {color}") # Prompt with type conversion age = await click.prompt("Your age", type=int) click.echo(f"You are {age} years old") # Hidden input for passwords password = await click.prompt( "Password", hide_input=True, confirmation_prompt=True ) click.echo(f"Password set ({len(password)} chars)") # Confirmation prompt if click.confirm("Continue with operation?"): click.echo("Proceeding...") else: click.echo("Cancelled") if __name__ == "__main__": interactive() # Usage: # $ python app.py # What's your name?: Alice # Hello, Alice! # Favorite color [blue]: # Your favorite color is blue # Your age: 25 # You are 25 years old # Password: # Repeat for confirmation: # Password set (8 chars) # Continue with operation? [y/N]: y # Proceeding... ``` -------------------------------- ### Command Chaining Group Example Source: https://github.com/python-trio/asyncclick/blob/main/docs/commands.rst Demonstrates how to enable command chaining by setting 'chain=True' when creating a click group. This allows multiple subcommands to be invoked sequentially in a single call. ```python import click @click.group(chain=True) def cli(): """A group that supports command chaining.""" pass @cli.command('validate') def validate(): """Validates the input.""" click.echo('validate') @cli.command('build') def build(): """Builds the project.""" click.echo('build') @cli.command('upload') def upload(): """Uploads the artifact.""" click.echo('upload') # Example of how to run this: # from click.testing import CliRunner # runner = CliRunner() # result = runner.invoke(cli, ['validate', 'build', 'upload']) # print(result.output) ``` -------------------------------- ### Validate Parameters with Asyncclick Callbacks Source: https://github.com/python-trio/asyncclick/blob/main/docs/advanced.rst This example shows how to use parameter callbacks for custom validation logic. The callback modifies values and raises errors if validation fails. It demonstrates how to validate the format of a string input. ```python def validate_rolls(ctx, param, value): if isinstance(value, tuple): return value try: rolls, _, dice = value.partition("d") return int(dice), int(rolls) except ValueError: raise click.BadParameter("format must be 'NdM'") @click.command() @click.option( "--rolls", type=click.UNPROCESSED, callback=validate_rolls, default="1d6", prompt=True, ) def roll(rolls): sides, times = rolls click.echo(f"Rolling a {sides}-sided dice {times} time(s)") ``` -------------------------------- ### Read Username from Environment Variable (Python) Source: https://github.com/python-trio/asyncclick/blob/main/docs/options.md Demonstrates how to define a Click option that reads its value from a specific environment variable. If the environment variable is not set, the option will not have a value. This example uses the 'USERNAME' environment variable. ```python import click @click.command() @click.option('--username', envvar='USERNAME') def greet(username): click.echo(f"Hello {username}!") # Example of how to run this with a specific environment variable: # from click.testing import CliRunner # runner = CliRunner() # result = runner.invoke(greet, env={'USERNAME': 'john'}) # print(result.output) ``` -------------------------------- ### Custom Parameter Type Implementation Source: https://github.com/python-trio/asyncclick/blob/main/docs/parameter-types.rst Explains how to create custom parameter types by subclassing `click.ParamType` and overriding the `convert` method. Provides an example of an integer type that handles hex and octal numbers. ```APIDOC ## DELETE /api/users/{userId} ### Description Deletes a specific user from the system using their unique identifier. ### Method DELETE ### Endpoint /api/users/{userId} ### Parameters #### Path Parameters - **userId** (string) - Required - The unique identifier of the user to delete. #### Query Parameters None #### Request Body None ### Request Example ``` DELETE /api/users/a1b2c3d4-e5f6-7890-1234-567890abcdef ``` ### Response #### Success Response (204) No content is returned upon successful deletion. #### Response Example (No content) ``` -------------------------------- ### Add Custom Shell Completion Support in Python Source: https://github.com/python-trio/asyncclick/blob/main/docs/shell-completion.md Enables support for custom shells by subclassing `ShellComplete` and registering it. The example demonstrates creating completion scripts and parsing completion arguments for a hypothetical 'mysh' shell. ```python from click.shell_completion import add_completion_class from click.shell_completion import ShellComplete from click.parser import split_arg_string import os _mysh_source = """\%(complete_func)s { response=$(%(complete_var)s=mysh_complete %(foo_bar)s) # parse response and set completions somehow } call-on-complete %(foo_bar)s %(complete_func)s """ @add_completion_class class MyshComplete(ShellComplete): name = "mysh" source_template = _mysh_source def get_completion_args(self): args = split_arg_string(os.environ["COMP_WORDS"]) if os.environ["COMP_PARTIAL"] == "1": incomplete = args.pop() return args, incomplete return args, "" def format_completion(self, item): return f"{item.type}\t{item.value}" ``` -------------------------------- ### Basic Group Creation and Command Nesting in Click Source: https://github.com/python-trio/asyncclick/blob/main/docs/commands-and-groups.rst Demonstrates creating a Click group using @click.group() and nesting commands within it using the @group.command() decorator. Invoking the group without a subcommand typically shows its help page. Requires the 'click' library. ```python import click @click.group() def greeting(): click.echo('Starting greeting ...') @greeting.command('say-hello') @click.option('--count', default=1) def hello(count): for x in range(count): click.echo("Hello!") # Example invocations (for testing/demonstration): # from click.testing import CliRunner # runner = CliRunner() # result_group = runner.invoke(greeting) # result_command = runner.invoke(greeting, args=['say-hello']) # result_help = runner.invoke(greeting, args=['say-hello', '--help']) ``` -------------------------------- ### Finding Application Folders with Click Source: https://github.com/python-trio/asyncclick/blob/main/docs/utils.md Shows how to use `click.get_app_dir` to locate the appropriate directory for per-user configuration files based on the operating system. This is useful for managing application settings across different platforms. ```python import os import click import ConfigParser APP_NAME = 'My Application' def read_config(): cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini') parser = ConfigParser.RawConfigParser() parser.read([cfg]) rv = {} for section in parser.sections(): for key, value in parser.items(section): rv[f"{section}.{key}"] = value return rv ``` -------------------------------- ### Testing CLI Commands with CliRunner in Python Source: https://context7.com/python-trio/asyncclick/llms.txt Demonstrates how to use CliRunner for isolated testing of asynchronous CLI commands. It simulates input and captures output and errors. Dependencies include asyncclick and pytest. ```python import asyncclick as click from asyncclick.testing import CliRunner import pytest @click.command() @click.option("--name", prompt="Your name") @click.option("--count", default=1, type=int) async def hello(name, count): """Say hello.""" for _ in range(count): click.echo(f"Hello, {name}!") @click.command() @click.option("--verbose", "-v", is_flag=True) @click.argument("filename") async def process(verbose, filename): """Process a file.""" if verbose: click.echo(f"Processing: {filename}", err=True) click.echo(f"Done: {filename}") # Test functions @pytest.mark.anyio async def test_hello(): runner = CliRunner() result = await runner.invoke(hello, ["--name", "Alice", "--count", "2"]) assert result.exit_code == 0 assert "Hello, Alice!" in result.output assert result.output.count("Hello, Alice!") == 2 @pytest.mark.anyio async def test_hello_with_prompt(): runner = CliRunner() result = await runner.invoke(hello, input="Bob\n") assert result.exit_code == 0 assert "Hello, Bob!" in result.output @pytest.mark.anyio async def test_process_verbose(): runner = CliRunner() result = await runner.invoke(process, ["-v", "test.txt"]) assert result.exit_code == 0 assert "Processing: test.txt" in result.stderr assert "Done: test.txt" in result.stdout @pytest.mark.anyio async def test_with_env(): runner = CliRunner(env={"MY_VAR": "test"}) result = await runner.invoke(hello, ["--name", "Test"]) assert result.exit_code == 0 ``` -------------------------------- ### Document Arguments via Docstring - Python Source: https://github.com/python-trio/asyncclick/blob/main/docs/documentation.md Explains that `click.argument` does not accept a `help` parameter. Arguments should be documented within the command's docstring, following Unix conventions. This example shows how to document a single argument. ```python @click.command() @click.argument('filename') def touch(filename): """Print FILENAME.""" click.echo(filename) ``` ```python @click.command() @click.argument('filename') def touch(filename): """Print FILENAME. FILENAME is the name of the file to check. """ click.echo(filename) ``` -------------------------------- ### Asyncclick Utilities API Source: https://github.com/python-trio/asyncclick/blob/main/docs/api.rst Reference for utility functions for input/output, prompting, and file handling. ```APIDOC ## Asyncclick Utilities ### Description This section lists utility functions for common command-line tasks like echoing output, prompting users, and managing files. ### Utilities - `echo`: Prints text to the console. - `echo_via_pager`: Echoes text using a pager. - `prompt`: Prompts the user for input. - `confirm`: Prompts the user for a yes/no confirmation. - `progressbar`: Displays a progress bar. - `clear`: Clears the terminal screen. - `style`: Styles text with colors and effects. - `unstyle`: Removes styling from text. - `secho`: Echoes styled text. - `edit`: Opens an editor for text input. - `launch`: Launches a URL or file. - `getchar`: Reads a single character from input. - `pause`: Pauses execution until Enter is pressed. - `get_binary_stream`: Gets a binary stream for input/output. - `get_text_stream`: Gets a text stream for input/output. - `open_file`: Opens a file with appropriate encoding. - `get_app_dir`: Gets the application directory path. - `format_filename`: Formats a filename for display. ``` -------------------------------- ### Launch Application or URL (Python) Source: https://github.com/python-trio/asyncclick/blob/main/docs/utils.md Launches the default application associated with a given URL or file. Can also be used to open a file manager and select a specific file by setting `locate=True`. This is useful for opening web browsers, file viewers, or navigating file systems. ```python click.launch("https://click.palletsprojects.com/") click.launch("/my/downloaded/file.txt", locate=True) ``` -------------------------------- ### Choice Type Example with Enum - Python Source: https://github.com/python-trio/asyncclick/blob/main/docs/parameter-types.rst Demonstrates using the click.Choice type with an Enum for command-line options. It shows how to define valid choices and handle case-insensitivity. The output reflects the selected enum member. ```python import enum class HashType(enum.Enum): MD5 = enum.auto() SHA1 = enum.auto() @click.command() @click.option('--hash-type', type=click.Choice(HashType, case_sensitive=False)) def digest(hash_type: HashType): click.echo(hash_type) ``` -------------------------------- ### Create Repo Pass Decorator with Asyncclick Source: https://github.com/python-trio/asyncclick/blob/main/docs/complex.rst Demonstrates how to create a custom decorator using `click.make_pass_decorator` to find the nearest 'Repo' object in the context. This is useful for commands that need access to a repository object, ensuring it's correctly passed down. ```python import asyncclick as click class Repo: pass pass_repo = click.make_pass_decorator(Repo) ``` -------------------------------- ### Basic Option Prompting with Click Source: https://github.com/python-trio/asyncclick/blob/main/docs/prompts.md Demonstrates how to use `click.option` with `prompt=True` to automatically ask the user for input if the option is not provided via the command line. The prompt string can be customized. ```python import click @click.command() @click.option('--name', prompt=True) def hello(name): click.echo(f"Hello {name}!") @click.command() @click.option('--name', prompt='Your name please') def hello_custom_prompt(name): click.echo(f"Hello {name}!") ``` -------------------------------- ### Custom Integer Parameter Type - Python Source: https://github.com/python-trio/asyncclick/blob/main/docs/parameter-types.rst Provides an example of implementing a custom parameter type by subclassing click.ParamType. This custom type, BasedIntParamType, extends integer handling to accept hex and octal number formats. ```python import click class BasedIntParamType(click.ParamType): name = "integer" def convert(self, value, param, ctx): if isinstance(value, int): return value ``` -------------------------------- ### Implement Password and Confirmation Prompts in AsyncClick Source: https://context7.com/python-trio/asyncclick/llms.txt Shows how to use AsyncClick's built-in features for handling sensitive user input, such as secure password entry with `hide_input=True` and `confirmation_prompt=True`, as well as custom prompt messages. ```python import asyncclick as click @click.command() @click.option( "--username", prompt=True, help="Account username." ) @click.option( "--password", prompt=True, hide_input=True, confirmation_prompt=True, help="Account password." ) @click.option( "--email", prompt="E-Mail Address", help="Contact email." ) async def register(username, password, email): """Register a new user account.""" click.echo(f"Registering user: {username}") click.echo(f"Email: {email}") click.echo(f"Password length: {len(password)} characters") @click.command() @click.confirmation_option(prompt="Are you sure you want to delete all data?") async def delete_all(): """Delete all data (requires confirmation).""" click.echo("Deleting all data...") if __name__ == "__main__": register() ``` -------------------------------- ### Pass Context and State with AsyncClick Decorators Source: https://context7.com/python-trio/asyncclick/llms.txt Explains how to manage and pass state between different commands in an AsyncClick application using `@click.pass_context` and `@click.pass_obj`. It also demonstrates creating custom decorators with `make_pass_decorator` for specific object types. ```python import asyncclick as click class Config: def __init__(self): self.verbose = False self.home = None pass_config = click.make_pass_decorator(Config, ensure=True) @click.group() @click.option("--verbose", "-v", is_flag=True, help="Enable verbose mode.") @click.option("--home", type=click.Path(), help="Project home directory.") @pass_config def cli(config, verbose, home): """A CLI with shared configuration.""" config.verbose = verbose config.home = home @cli.command() @click.argument("name") @pass_config async def init(config, name): """Initialize a new project.""" if config.verbose: click.echo(f"Home directory: {config.home}") click.echo(f"Initializing project: {name}") @cli.command() @click.pass_context async def status(ctx): """Show current status using context.""" config = ctx.find_object(Config) click.echo(f"Verbose: {config.verbose}") click.echo(f"Home: {config.home}") click.echo(f"Command path: {ctx.command_path}") if __name__ == "__main__": cli() ``` -------------------------------- ### Custom Parameter Type for Environment Variables with Click Source: https://github.com/python-trio/asyncclick/blob/main/docs/shell-completion.md Defines a custom parameter type 'EnvVarType' that provides shell completion for environment variable names starting with the incomplete input. It overrides the shell_complete method to filter environment variables. ```python import os import click from click.shell_completion import CompletionItem from click.types import ParamType class EnvVarType(ParamType): name = "envvar" def shell_complete(self, ctx, param, incomplete): return [ CompletionItem(name) for name in os.environ if name.startswith(incomplete) ] @click.command() @click.option("--ev", type=EnvVarType()) def cli(ev): click.echo(os.environ[ev]) ``` -------------------------------- ### Define CLI Command with Asyncclick Source: https://github.com/python-trio/asyncclick/blob/main/docs/entry-points.rst This Python code defines a simple command-line interface (CLI) command using the asyncclick library. It requires the 'click' package to be installed. The function decorated with `@click.command()` becomes an executable command. ```python import click @click.command() def cli(): """Prints a greeting.""" click.echo("Hello, World!") ``` -------------------------------- ### Create Repo Pass Decorator with Ensure Object (Asyncclick) Source: https://github.com/python-trio/asyncclick/blob/main/docs/complex.rst Illustrates creating a decorator with `ensure=True`. This ensures that a 'Repo' object is always available in the context, creating one if it doesn't exist. This is useful for commands that should run even if their parent commands don't set up the context object. ```python import asyncclick as click class Repo: def __init__(self): pass pass_repo = click.make_pass_decorator(Repo, ensure=True) ```