### Cyclopts Development Setup with uv Source: https://cyclopts.readthedocs.io/en/stable/Installation Sets up the Cyclopts project for development using uv. This involves cloning the repository, navigating into the directory, and synchronizing dependencies with all extras. ```shell git clone https://github.com/BrianPugh/cyclopts.git cd cyclopts uv sync --all-extras ``` -------------------------------- ### Install Cyclopts from GitHub Source: https://cyclopts.readthedocs.io/en/stable/Installation Installs the Cyclopts Python package directly from its GitHub repository. This is useful for installing the latest development version or a specific commit. ```shell python -m pip install git+https://github.com/BrianPugh/cyclopts.git ``` -------------------------------- ### Example Command Execution Source: https://cyclopts.readthedocs.io/en/stable/api These examples illustrate the execution of commands defined in the application. The first two show simple command outputs, while the third demonstrates invoking the lazily loaded 'create' command. ```bash $ my-script foo foo! $ my-script buzz bar! $ my-script create ``` -------------------------------- ### Create Basic Cyclopts App Source: https://cyclopts.readthedocs.io/en/stable/getting_started Demonstrates the simplest Cyclopts application. It registers a default function that prints 'Hello World!' when no command-line arguments are provided. This requires the 'cyclopts' library. ```python from cyclopts import App app = App() @app.default def main(): print("Hello World!") if __name__ == "__main__": app() ``` -------------------------------- ### Meta App Command Execution Example Source: https://cyclopts.readthedocs.io/en/stable/meta_app Illustrates the command-line execution of the meta app example. It shows how the custom launcher processes arguments and then executes the 'foo' command with the provided arguments. ```bash $ my-script --user=Bob foo 3 Hello Bob Looping! 0 Looping! 1 Looping! 2 ``` -------------------------------- ### Activating Virtual Environment for `cyclopts run` Source: https://cyclopts.readthedocs.io/en/stable/shell_completion This example shows the necessary steps to activate a Python virtual environment and then use `cyclopts run` to execute a development script within that environment, ensuring access to installed packages and the correct Python interpreter. ```bash $ source .venv/bin/activate # or your venv activation method $ cyclopts run myapp.py ``` -------------------------------- ### Example CLI Usage for types.Json Source: https://cyclopts.readthedocs.io/en/stable/api Demonstrates how to use the `types.Json` annotation in a Cyclopts application and provides an example of invoking it from the command line with a JSON string argument. ```bash $ my-script '{"foo": 1, "bar": 2}' {'foo': 1, 'bar': 2} ``` -------------------------------- ### Example CLI Invocation for Custom Command Source: https://cyclopts.readthedocs.io/en/stable/meta_app This is an example of how to invoke the custom command defined in the previous snippet from the command line. It shows the expected input format and the corresponding output. ```bash $ my-script create --user Alice 30 Creating user Alice with age 30. ``` -------------------------------- ### Run Simple Cyclopts Application with `cyclopts.run()` Source: https://cyclopts.readthedocs.io/en/stable/getting_started Illustrates the use of the `cyclopts.run()` function for creating simple CLI applications. This function takes a single callable and automatically sets it up as the application's main command, offering a more concise API than the `App` class for basic needs. ```python import cyclopts def main(name: str, count: int): for _ in range(count): print(f"Hello {name}!") if __name__ == "__main__": cyclopts.run(main) ``` -------------------------------- ### Manual Shell Completion Installation in Python Source: https://cyclopts.readthedocs.io/en/stable/shell_completion This Python snippet illustrates how to manually install shell completion using `App.install_completion`. It covers installing for the current shell, specifying a shell type, and directing the output to a custom file path. ```python from cyclopts import App from pathlib import Path app = App(name="myapp") # Install for current shell install_path = app.install_completion() print(f"Installed completion to {install_path}") # Install for specific shell install_path = app.install_completion(shell="zsh") # Install to custom location install_path = app.install_completion( shell="bash", output=Path("/custom/path/completion.sh"), ) ``` -------------------------------- ### Cyclopts Help Message with Docstring Parameters Source: https://cyclopts.readthedocs.io/en/stable/vs_typer/help_defaults/README This Cyclopts example demonstrates a more idiomatic way to define command-line interfaces using docstrings for parameter descriptions. It achieves the same clean help output as the previous example. ```python import cyclopts from pathlib import Path cyclopts_app = cyclopts.App() @cyclopts_app.default() def compress(src: Path, dst: Path = Path("out.zip")): """Compress a file. Parameters ---------- src: Path File to compress. dst: Path Path to save compressed data to. """ print(f"Compressing data from {src} to {dst}") cyclopts_app(["--help"]) # ╭─ Parameters ───────────────────────────────────────────────────────╮ # │ * SRC,--src File to compress. [required] │ # │ DST,--dst Path to save compressed data to. [default: out.zip] │ # ╰────────────────────────────────────────────────────────────────────╯ ``` -------------------------------- ### Add Application-Level Help to Cyclopts CLI Source: https://cyclopts.readthedocs.io/en/stable/getting_started Demonstrates how to set a custom help message for a Cyclopts CLI application using the `help` parameter during `App` initialization. This message is displayed when the `--help` flag is used. ```python from cyclopts import App app = App(help="Help string for this demo application.") @app.default def main(name: str, count: int): for _ in range(count): print(f"Hello {name}!") if __name__ == "__main__": app() ``` -------------------------------- ### Install Cyclopts from PyPI Source: https://cyclopts.readthedocs.io/en/stable/Installation Installs the Cyclopts Python package using pip from the Python Package Index (PyPI). This is the standard method for users who want to utilize the package. ```shell python -m pip install cyclopts ``` -------------------------------- ### Install Cyclopts with MkDocs Support Source: https://cyclopts.readthedocs.io/en/stable/mkdocs_integration This command installs the Cyclopts library along with the necessary dependencies for MkDocs integration. It allows you to use Cyclopts directives within your MkDocs documentation. ```bash pip install cyclopts[mkdocs] ``` -------------------------------- ### Execute Async Command with Cyclopts Source: https://cyclopts.readthedocs.io/en/stable/api Demonstrates how to define and run an asynchronous command using Cyclopts within an existing asyncio event loop. This example showcases a simple async function that sleeps and returns a string. ```python import asyncio from cyclopts import App app = App() @app.command async def my_async_command(): await asyncio.sleep(1) return "Done!" ``` -------------------------------- ### Add Parameter Help Documentation to Cyclopts CLI Source: https://cyclopts.readthedocs.io/en/stable/getting_started Shows how to add detailed help documentation for command-line parameters by utilizing function docstrings. Cyclopts supports various docstring formats (ReST, Google, Numpydoc, Epydoc) to parse parameter descriptions. ```python from cyclopts import App app = App() @app.default def main(name: str, count: int): """Help string for this demo application. Parameters ---------- name: str Name of the user to be greeted. count: int Number of times to greet. """ for _ in range(count): print(f"Hello {name}!") if __name__ == "__main__": app() ``` -------------------------------- ### TOML Configuration Example - Character Counter CLI Source: https://cyclopts.readthedocs.io/en/stable/config_file Demonstrates setting up a CLI tool that counts character occurrences in a file using TOML configuration. It specifies the TOML file, root keys for namespacing, and enables searching parent directories. The example shows how default values from `pyproject.toml` override CLI arguments. ```python # character-counter.py import cyclopts from cyclopts import App from pathlib import Path app = App( name="character-counter", config=cyclopts.config.Toml( "pyproject.toml", # Name of the TOML File root_keys=["tool", "character-counter"], # The project's namespace in the TOML. # If "pyproject.toml" is not found in the current directory, # then iteratively search parenting directories until found. search_parents=True, ), ) @app.command def count(filename: Path, *, character="-"): print(filename.read_text().count(character)) if __name__ == "__main__": app() ``` -------------------------------- ### Meta Command Execution Example Source: https://cyclopts.readthedocs.io/en/stable/meta_app Shows the command-line execution when a meta command ('info') is called. This demonstrates that the meta command is executed directly, bypassing the default meta app launcher. ```bash $ my-script info CLI didn't have to provide --user to call this. ``` -------------------------------- ### Register Install Completion Command Source: https://cyclopts.readthedocs.io/en/stable/api Registers a command for installing shell completion. This is a convenience method that creates a command which calls `install_completion()`. ```APIDOC ## POST /register_install_completion_command ### Description Registers a command for installing shell completion. This is a convenience method that creates a command which calls `install_completion()`. ### Method POST ### Endpoint /register_install_completion_command ### Parameters #### Query Parameters - **name** (str | Iterable[str]) - Optional - Command name(s) for the install completion command. Defaults to "--install-completion". - **add_to_startup** (bool) - Optional - If True (default), adds source line to shell RC file to ensure completion is loaded. Set to False if completions are already configured to auto-load. #### Request Body - **kwargs** (dict) - Optional - Additional keyword arguments to pass to `command()`. Can be used to customize the command registration (e.g., help, group, help_flags, version_flags). ### Request Example ```json { "name": "--setup-completion", "add_to_startup": false, "kwargs": { "help": "Install shell completion for myapp.", "group": "Setup", "help_flags": [] } } ``` ### Response #### Success Response (200) - **message** (str) - Indicates successful registration. #### Response Example ```json { "message": "Install completion command registered successfully." } ``` ``` -------------------------------- ### Programmatic Shell Completion Installation in Python Source: https://cyclopts.readthedocs.io/en/stable/shell_completion This Python code demonstrates how to integrate shell completion installation directly into a CLI application using `App.register_install_completion_command`. Users can then install completion by running a command like `myapp --install-completion`. ```python from cyclopts import App app = App(name="myapp") app.register_install_completion_command() # Your commands here... if __name__ == "__main__": app() ``` -------------------------------- ### Install Shell Completion Script with Cyclopts Source: https://cyclopts.readthedocs.io/en/stable/api Installs shell completion scripts for Zsh, Bash, or Fish to their appropriate locations. It can auto-detect the shell or use a specified type, and optionally add the script to the shell's startup files. The function returns the path where the script was installed. Dependencies include the 'cyclopts' library and 'pathlib'. Raises ShellDetectionError if auto-detection fails. ```python app = App(name="myapp") path = app.install_completion() ``` ```python path = app.install_completion(shell="zsh") ``` ```python path = app.install_completion(output=Path("/custom/path")) ``` ```python path = app.install_completion(shell="bash", add_to_startup=False) ``` -------------------------------- ### Typer Application Example Source: https://cyclopts.readthedocs.io/en/stable/index An equivalent Typer application demonstrating command-line argument parsing using Annotated types, Enums, and custom parsers. It aims to replicate the functionality of the Cyclopts example. ```python import typer from typing import Annotated, Literal from enum import Enum app = typer.Typer() class Environment(str, Enum): dev = "dev" staging = "staging" prod = "prod" def replica_parser(value: str): if value == "default": return 10 elif value == "performance": return 20 else: return int(value) def _version_callback(value: bool): if value: print("0.0.0") raise typer.Exit() @app.callback() def callback( version: Annotated[ bool | None, typer.Option("--version", callback=_version_callback) ] = None, ): pass @app.command(help="Deploy code to an environment.") def deploy( env: Annotated[Environment, typer.Argument(help="Environment to deploy to.")], replicas: Annotated[ int, typer.Argument( parser=replica_parser, help="Number of workers to spin up.", ), ] = replica_parser("default"), ): print(f"Deploying to {env.name} with {replicas} replicas.") if __name__ == "__main__": app() ``` -------------------------------- ### Basic CLI Version Check Example Source: https://cyclopts.readthedocs.io/en/stable/version Demonstrates the standard command-line interface for checking an application's version using the `--version` flag. This is a common pattern for CLI tools. ```bash $ my-application --version 7.5.8 ``` -------------------------------- ### Install Shell Completion Source: https://cyclopts.readthedocs.io/en/stable/api Generates and installs shell completion scripts for the application. It supports auto-detection of the shell or explicit specification, custom output paths, and options to modify shell startup files. ```APIDOC ## POST /install_completion ### Description Generates and installs shell completion scripts for the application. It supports auto-detection of the shell or explicit specification, custom output paths, and options to modify shell startup files. ### Method POST ### Endpoint /install_completion ### Parameters #### Query Parameters - **shell** (Literal['zsh', 'bash', 'fish'] | None) - Optional - Shell type for completion. If not specified, attempts to auto-detect current shell. - **output** (Path | None) - Optional - Output path for the completion script. If not specified, uses shell-specific default. - **add_to_startup** (bool) - Optional - If True (default), adds source line to shell RC file to ensure completion is loaded. Set to False if completions are already configured to auto-load. ### Response #### Success Response (200) - **path** (Path) - Path where the completion script was installed. #### Response Example ```json { "path": "/home/user/.zsh/completions/_myapp" } ``` ### Raises - **ShellDetectionError** -- If shell is None and auto-detection fails. - **ValueError** -- If shell type is unsupported. ``` -------------------------------- ### Cyclopts Application Example Source: https://cyclopts.readthedocs.io/en/stable/index A concise Cyclopts application demonstrating command-line argument parsing with literal types and default values. It includes type validation and custom logic for specific argument values. ```python import cyclopts from typing import Literal app = cyclopts.App() @app.command def deploy( env: Literal["dev", "staging", "prod"], replicas: int | Literal["default", "performance"] = "default", ): """Deploy code to an environment. Parameters ---------- env Environment to deploy to. replicas Number of workers to spin up. """ if replicas == "default": replicas = 10 elif replicas == "performance": replicas = 20 print(f"Deploying to {env} with {replicas} replicas.") if __name__ == "__main__": app() ``` -------------------------------- ### Register Install Completion Command in Python Source: https://cyclopts.readthedocs.io/en/stable/api Registers a command to install shell completion for an application. It can customize the command name, whether to add it to startup files, and pass additional arguments for command registration. This is a convenience method that calls install_completion(). ```python from cyclopts import App app = App(name="myapp") # Register with default name app.register_install_completion_command() # Use a custom command name app.register_install_completion_command(name="--setup-completion") # Customize help text app.register_install_completion_command(help="Install shell completion for myapp.") # Customize command registration (group and help flags) app.register_install_completion_command(group="Setup", help_flags=[]) # Install without modifying RC files app.register_install_completion_command(add_to_startup=False) # Example of running the app after registration (responds to --install-completion) # app() ``` -------------------------------- ### Import Path Format Examples Source: https://cyclopts.readthedocs.io/en/stable/lazy_loading Illustrates various ways to specify import paths for lazy loading commands, including simple functions, nested modules, and importing App instances. ```python # Simple function in a module app.command("myapp.commands:create_user") # Nested module path app.command("myapp.admin.database.operations:migrate") # Import an App instance, exposed to the CLI as "admin" app.command("myapp.admin:admin_app", name="admin") ``` -------------------------------- ### Launch Cyclopts Interactive Shell Source: https://cyclopts.readthedocs.io/en/stable/cookbook/interactive_help Demonstrates how to create a Cyclopts application with commands and launch an interactive shell. This code defines two commands, 'foo' and 'bar', and then starts a blocking interactive shell session. ```python from cyclopts import App app = App() @app.command def foo(p1): """Foo Docstring. Parameters ---------- p1: str Foo's first parameter. """ print(f"foo {p1}") @app.command def bar(p1): """Bar Docstring. Parameters ---------- p1: str Bar's first parameter. """ print(f"bar {p1}") # A blocking call, launching an interactive shell. app.interactive_shell(prompt="cyclopts> ") ``` -------------------------------- ### Python CLI with Cyclopts - Basic Hello World Source: https://cyclopts.readthedocs.io/en/stable/vs_fire/README Demonstrates a simple 'hello' command using the Cyclopts library. Cyclopts uses type hints for argument parsing, providing more control than Fire. This example shows the equivalent 'hello' function and how Cyclopts handles input, which differs from Fire's behavior for non-string types. ```python import cyclopts app = cyclopts.App() @app.default def hello(name: str = "World"): print(f"{name=} {type(name)=}") if __name__ == "__main__": app() ``` -------------------------------- ### Configure App Backend with Cyclopts Source: https://cyclopts.readthedocs.io/en/stable/api Demonstrates how to initialize a Cyclopts App with a specific asynchronous backend ('asyncio' or 'trio') and how to override the backend for individual calls. ```python from cyclopts import App app = App(backend="asyncio") @app.default async def main(): await some_async_operation() app() app(backend="trio") # Override the app's backend for this call ``` -------------------------------- ### Configure Console Script Entrypoint (setup.py) Source: https://cyclopts.readthedocs.io/en/stable/packaging Configures a console script entrypoint for older Python projects using the `setup.py` file. This method uses `setuptools.setup` and the `entry_points` argument to define executable scripts. It specifies the script name and the Python module and function to execute. ```python # setup.py from setuptools import setup setup( # There should be a lot more fields populated here. entry_points={ "console_scripts": [ "my-package = mypackage.__main__:main", ] }, ) ``` -------------------------------- ### Disabling Automatic Shell RC File Modification Source: https://cyclopts.readthedocs.io/en/stable/shell_completion This Python example demonstrates how to register the completion installation command without automatically modifying the user's shell RC file. This provides more control over shell configuration. ```python app.register_install_completion_command(add_to_startup=False) ``` -------------------------------- ### Python CLI with Fire - Basic Hello World Source: https://cyclopts.readthedocs.io/en/stable/vs_fire/README Demonstrates a simple 'hello' command using the Fire library. Fire parses command-line arguments as Python expressions, inferring types from values rather than function signatures. This example shows how string, integer, and boolean inputs are handled. ```python import fire def hello(name: str = "World"): print(f"{name=} {type(name)=}") if __name__ == "__main__": fire.Fire(hello) ``` -------------------------------- ### App Initialization and Configuration Source: https://cyclopts.readthedocs.io/en/stable/api This section details the parameters available during the initialization of a Cyclopts App, allowing for fine-grained control over its behavior. ```APIDOC ## App Initialization Parameters ### Description Parameters that can be passed to the `App` constructor to configure its behavior. ### Method `App(...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **delimiter** (string | None) - All tokens after this delimiter will be force-interpreted as positional arguments. If not set, attempts to inherit from parenting `App`, eventually defaulting to POSIX-standard `--`. Set to an empty string to disable. - **suppress_keyboard_interrupt** (bool) - If the application receives a keyboard interrupt (Ctrl-C), suppress the error message and exit gracefully. Set to `False` to let `KeyboardInterrupt` propagate normally. Defaults to `True`. - **backend** (Literal['asyncio', 'trio'] | None) - The async backend to use when executing async commands. If not set, attempts to inherit from parenting `App`, eventually defaulting to `"asyncio"`. - **result_action** (Literal[...] | Callable[[Any], Any] | Iterable[Literal[...] | Callable[[Any], Any]] | None) - Controls how `App.__call__()` and `App.run_async()` handle command return values. By default (`"print_non_int_sys_exit"`), the app will call `sys.exit()` with an appropriate exit code. This default was chosen for consistent functionality between standalone scripts, and console entrypoints. Can be a predefined literal string, a custom callable that takes the result and returns a processed value, or a sequence of actions to be applied left-to-right in a pipeline. ### Request Example ```python from cyclopts import App app = App(backend="asyncio", suppress_keyboard_interrupt=False) ``` ### Response #### Success Response (200) N/A (This describes constructor parameters, not a request/response cycle) #### Response Example N/A ``` -------------------------------- ### Add Single Argument to Cyclopts App Source: https://cyclopts.readthedocs.io/en/stable/getting_started Extends a basic Cyclopts application to accept a single string argument. The 'main' function is registered as the default action and takes a 'name' parameter, printing a personalized greeting. Cyclopts defaults to string type if no type hint is provided. ```python from cyclopts import App app = App() @app.default def main(name): print(f"Hello {name}!") if __name__ == "__main__": app() ``` -------------------------------- ### Handle Multiple Typed Arguments in Cyclopts Source: https://cyclopts.readthedocs.io/en/stable/getting_started Illustrates how to define a Cyclopts application with multiple arguments, including type hints for strings, integers, and booleans. The 'main' function accepts 'name' (str), 'count' (int), and 'formal' (bool) to control the output. Cyclopts natively supports Python's built-in types and handles flags for boolean arguments. ```python from cyclopts import App app = App() @app.default def main(name: str, count: int, formal: bool = False): for _ in range(count): if formal: print(f"Hello {name}!") else: print(f"Hey {name}!") if __name__ == "__main__": app() ``` -------------------------------- ### Basic App Launch with Cyclopts Source: https://cyclopts.readthedocs.io/en/stable/meta_app Demonstrates the standard way to launch a Cyclopts application by instantiating the App class and calling it. This is the foundational step before introducing meta apps. ```python from cyclopts import App app = App() # Register some commands here (not shown) app() # Run the app ``` -------------------------------- ### Install Cyclopts using pip Source: https://cyclopts.readthedocs.io/en/stable/index Installs the Cyclopts package using pip. Requires Python version 3.10 or higher. ```bash pip install cyclopts ``` -------------------------------- ### Configure Console Script Entrypoint (setup.cfg) Source: https://cyclopts.readthedocs.io/en/stable/packaging Configures a console script entrypoint for Python packages using the `setup.cfg` file. This INI-style configuration is used by setuptools to define package metadata, including console scripts. It lists the script name and the Python module and function to be executed. ```ini # setup.cfg [options.entry_points] console_scripts = my-package = mypackage.__main__:main ``` -------------------------------- ### Define a CLI Group with Plain Help Formatting Source: https://cyclopts.readthedocs.io/en/stable/api This snippet demonstrates how to create a CLI group named 'Simple Options' and configure its help formatter to 'plain' for a simplified output. It utilizes the cyclopts library and requires importing App, Group, and Parameter. ```python from cyclopts import App, Group, Parameter from cyclopts.help import DefaultFormatter, PanelSpec from typing import Annotated app = App() # Using string literal simple_group = Group( "Simple Options", help_formatter="plain" ) ``` -------------------------------- ### Setting Command Help via Decorator Source: https://cyclopts.readthedocs.io/en/stable/help Illustrates how to provide a specific help string for a command using the `help` argument in the `@app.command` decorator. This method offers high precedence for defining command-level help text. ```python import cyclopts app = cyclopts.App() @app.command(help="This is the highest precedence help-string for 'bar'.") def bar(): pass ``` -------------------------------- ### Configure Console Script Entrypoint (Poetry) Source: https://cyclopts.readthedocs.io/en/stable/packaging Configures a console script entrypoint for Python projects managed by Poetry using the `pyproject.toml` file. This section within `[tool.poetry]` defines executable scripts, specifying the script name and the Python module and function to run. ```toml # pyproject.toml [tool.poetry.scripts] my-package = "mypackage.__main__:main" ``` -------------------------------- ### Python CLI Application Entrypoint (__main__.py) Source: https://cyclopts.readthedocs.io/en/stable/packaging Defines a basic Cyclopts application within a Python module that can be executed using the `python -m` command. It imports Cyclopts, creates an App instance, defines a command, and includes the standard `if __name__ == "__main__":` block to run the app. ```python # mypackage/__main__.py import cyclopts app = cyclopts.App() @app.command def foo(name: str): print(f"Hello {name}!") if __name__ == "__main__": app() ``` -------------------------------- ### Get User Input with Text Editor (Python) Source: https://cyclopts.readthedocs.io/en/stable/api Launches the user's default text editor to get text input. Supports initial text, fallback editors, custom paths, encoding, and saving requirements. Raises various EditorErrors if issues occur. ```python import cyclopts try: text = cyclopts.edit(initial_text='Enter your text here.') print("You entered:", text) except cyclopts.EditorError as e: print(f"An editor error occurred: {e}") ``` -------------------------------- ### Python CLI Argument Parsing with Cyclopts Source: https://cyclopts.readthedocs.io/en/stable/api Demonstrates basic command-line interface structure using Cyclopts. It defines commands like 'beta' and 'alpha' with associated help descriptions, and includes options for displaying help and version information. ```python Usage: demo.py COMMAND ╭─ Commands ──────────────────────────────────────────────────╮ │ beta Beta help description. │ │ alpha Alpha help description. │ │ --help -h Display this message and exit. │ │ --version Display application version. │ ╰─────────────────────────────────────────────────────────────╯ ``` -------------------------------- ### Typer: Positional Arguments Example Source: https://cyclopts.readthedocs.io/en/stable/vs_typer/positional_or_keyword/README This code snippet demonstrates how to use Typer with positional arguments for a command. It defines a simple 'mv' command that takes 'src' and 'dst' as parameters and prints them. The example shows the command working correctly when arguments are provided positionally. ```python import typer typer_app = typer.Typer() @typer_app.command() def mv(src, dst): print(f"Moving {src} -> {dst}") typer_app(["foo", "bar"], standalone_mode=False) # Moving foo -> bar ``` -------------------------------- ### Help Command Source: https://cyclopts.readthedocs.io/en/stable/api Prints the help page for the application. It can interpret tokens to traverse the command structure or default to sys.argv. A custom console can be provided for output. ```APIDOC ## GET /help ### Description Prints the help page for the application. It can interpret tokens to traverse the command structure or default to sys.argv. A custom console can be provided for output. ### Method GET ### Endpoint /help ### Parameters #### Query Parameters - **tokens** (None | str | Iterable[str]) - Optional - Tokens to interpret for traversing the application command structure. If not provided, defaults to `sys.argv`. - **console** (Console) - Optional - Console to print help and runtime Cyclopts errors. If not provided, follows the resolution order defined in `App.console`. ``` -------------------------------- ### Get Subapp by Key Source: https://cyclopts.readthedocs.io/en/stable/api Retrieves a subapp associated with a given command string key. ```APIDOC ## Get Subapp by Key (`__getitem__`) ### Description Access a registered subapp using its command name as the key. ### How it Works - All commands are registered as subapps within Cyclopts. - The actual command handler for a subapp is located at `app[key].default_command`. - If a command was registered using a lazy loading import path string, it will be imported and resolved only when first accessed via this method. ### Example Usage ```python from cyclopts import App app = App() # Registering a subapp sub_app = App(name="my_subapp") app.command(sub_app) # Accessing the subapp retrieved_subapp = app["my_subapp"] # Accessing the default command of the subapp (if defined) # print(retrieved_subapp.default_command) @app["my_subapp"].command def sub_command(): print("Executing subcommand.") # Now, app["my_subapp"].default_command would point to sub_command ``` ``` -------------------------------- ### Typer: Keyword Arguments Failure Example Source: https://cyclopts.readthedocs.io/en/stable/vs_typer/positional_or_keyword/README This code snippet illustrates a limitation in Typer where parameters cannot be specified as keywords. It attempts to run the same 'mv' command as the previous example, but this time providing 'src' and 'dst' as keyword arguments. The output shows that Typer fails with an 'No such option' error. ```python print("Typer keyword:") typer_app(["--src", "foo", "--dst", "bar"], standalone_mode=False) # No such option: --src ``` -------------------------------- ### Typer Example: Handling Optional Lists Source: https://cyclopts.readthedocs.io/en/stable/vs_typer/optional_list/README Demonstrates how Typer handles optional list arguments. When no list is provided via CLI, Typer passes an empty list by default, which differs from the expected `None` or a default list value. This example shows the default behavior and how to manually set a default if needed. ```python import typer from typing import Optional typer_app = typer.Typer() @typer_app.command() def foo(favorite_numbers: Optional[list[int]] = None): if favorite_numbers is None: favorite_numbers = [1, 2, 3] print(f"My favorite numbers are: {favorite_numbers}") typer_app(["--favorite-numbers", "100", "--favorite-numbers", "200"], standalone_mode=False) # My favorite numbers are: [100, 200] typer_app([], standalone_mode=False) # My favorite numbers are: [] ``` -------------------------------- ### Combine Panel and Table Help Customizations in Cyclopts Source: https://cyclopts.readthedocs.io/en/stable/help_customization This example demonstrates how to combine custom panel and table specifications for command-line help messages using Cyclopts. It allows for distinct styling of different help sections, such as borders and padding. Dependencies include 'cyclopts' and 'rich'. ```python from cyclopts import App from cyclopts.help import DefaultFormatter, PanelSpec, TableSpec from rich.box import ROUNDED app = App( help_formatter=DefaultFormatter( panel_spec=PanelSpec( box=ROUNDED, border_style="cyan", padding=(0, 1), ), table_spec=TableSpec( show_header=False, show_lines=False, padding=(0, 1), ) ) ) @app.default def main(path: str, verbose: bool = False): """Process a file with combined customizations.""" print(f"Processing {path}") if __name__ == "__main__": app() ``` -------------------------------- ### Setting App-Level Help Source: https://cyclopts.readthedocs.io/en/stable/help Shows how to define help text at the `App` level, which can be inherited by subcommands. This is useful for setting a default help message for the entire application or specific sub-applications. ```python import cyclopts app = cyclopts.App(help="This help string has highest precedence at the app-level.") sub_app = cyclopts.App(help="This is the help string for the 'foo' subcommand.") app.command(sub_app, name="foo") app.command(sub_app, name="foo", help="This is illegal and raises a ValueError.") ``` -------------------------------- ### Parameter json_dict and json_list Source: https://cyclopts.readthedocs.io/en/stable/api Enables parsing of JSON-formatted strings for dictionary or list types when specified as keyword options and starting with '{' or '[' respectively. ```APIDOC ## POST /api/data ### Description This endpoint shows how `json_dict` and `json_list` parameters can parse JSON strings directly from the command line. ### Method POST ### Endpoint /api/data ### Parameters #### Query Parameters - **json_dict_data** (dict) - Optional - Accepts a JSON string representing a dictionary. - **json_list_data** (list) - Optional - Accepts a JSON string representing a list. ### Request Example ```json { "json_dict_data": "{\"key\": \"value\"}", "json_list_data": "[1, 2, 3]" } ``` ### Response #### Success Response (200) - **parsed_dict** (dict) - The parsed dictionary data. - **parsed_list** (list) - The parsed list data. #### Response Example ```json { "parsed_dict": { "key": "value" }, "parsed_list": [ 1, 2, 3 ] } ``` ``` -------------------------------- ### Get Subapp from Command String Source: https://cyclopts.readthedocs.io/en/stable/api Illustrates how to retrieve a subapp using a command string as a key. This is useful for accessing commands registered as subapps, including those loaded lazily. ```python from cyclopts import App app = App() app.command(App(name="foo")) @app["foo"].command def bar(): print("Running bar.") app() ``` -------------------------------- ### Subclassing StdioPath for Custom Trigger Strings Source: https://cyclopts.readthedocs.io/en/stable/api Provides examples of subclassing `StdioPath` to define custom trigger strings for standard input and output. This allows for flexibility in how stdin/stdout streams are represented in your application. ```python from cyclopts.types import StdioPath # Simple: different trigger string class StdinPath(StdioPath): STDIO_STRING = "STDIN" class StdoutPath(StdioPath): STDIO_STRING = "STDOUT" ``` -------------------------------- ### Decorating Converters with Parameter Source: https://cyclopts.readthedocs.io/en/stable/api Demonstrates how to decorate converter functions with `Parameter` to define reusable conversion logic. It shows how to control token consumption with `n_tokens` and how to combine with `accepts_keys` for complex object loading. The example also illustrates automatic inheritance of parameter settings when a converter is used in an annotation. ```python from cyclopts import App, Parameter from typing import Annotated # Assume fetch_from_db is defined elsewhere def fetch_from_db(value): pass @Parameter(n_tokens=1, accepts_keys=False) def load_from_id(type_, tokens): """Load object from database by ID.""" return fetch_from_db(tokens[0].value) app = App() @app.default def main(obj: Annotated[MyType, Parameter(converter=load_from_id)]): # Automatically inherits n_tokens=1 and accepts_keys=False pass ``` -------------------------------- ### Populating Help from Docstrings Source: https://cyclopts.readthedocs.io/en/stable/help Demonstrates how Cyclopts parses docstrings of default commands to generate help information. It covers extracting short and long descriptions for the application and its parameters. ```python import cyclopts app = cyclopts.App() app.command(cyclopts.App(), name="foo") @app.default def bar(val1: str): """This is the primary application docstring. Parameters ---------- val1: str This will be parsed for val1 help-string. """ @app["foo"].default # You can access sub-apps like a dictionary. def foo_handler(): """This will be shown for the "foo" command.""" ``` -------------------------------- ### Automatic Reference Labels Example Source: https://cyclopts.readthedocs.io/en/stable/sphinx_integration Demonstrates how the Sphinx directive automatically generates RST reference labels for commands, enabling cross-referencing. The anchor format is `cyclopts-{app-name}-{command-path}`. ```rst You can reference these commands elsewhere in your documentation using `:ref:`cyclopts-myapp-deploy``. ``` -------------------------------- ### Assemble and Print Argument Collection Source: https://cyclopts.readthedocs.io/en/stable/api Demonstrates how to assemble an argument collection from a Cyclopts App and print the name, hint, and keys for each argument. This is useful for inspecting the structure of parsed arguments. ```python from cyclopts import App, Parameter from dataclasses import dataclass from typing import Annotated app = App() @dataclass class User: id: int name: Annotated[str, Parameter(name="--fullname")] @app.default def main(user: User): pass for argument in app.assemble_argument_collection(): print(f"name: {argument.name:16} hint: {str(argument.hint):16} keys: {str(argument.keys)}") ``` -------------------------------- ### Implementing a Meta App in Cyclopts Source: https://cyclopts.readthedocs.io/en/stable/meta_app Shows how to create a meta app in Cyclopts. The meta app inherits configuration from its parent and merges its help page. It uses a default command to handle custom launching logic and pass remaining tokens to the primary app. ```python from cyclopts import App, Group, Parameter from typing import Annotated app = App() # Rename the meta's "Parameter" -> "Session Parameters". # Set sort_key so it will be drawn higher up the help-page. app.meta.group_parameters = Group("Session Parameters", sort_key=0) @app.command def foo(loops: int): for i in range(loops): print(f"Looping! {i}") @app.meta.default def my_app_launcher(*tokens: Annotated[str, Parameter(show=False, allow_leading_hyphen=True)], user: str): print(f"Hello {user}") app(tokens) app.meta() ``` -------------------------------- ### Use Async Commands in Cyclopts Source: https://cyclopts.readthedocs.io/en/stable/commands Provides an example of an asynchronous command in Cyclopts. When an async command is called, Cyclopts automatically creates an event loop (defaulting to asyncio) to run it. ```python import asyncio from cyclopts import App app = App() @app.command async def foo(): await asyncio.sleep(10) app() ``` -------------------------------- ### Parse JSON Dict Strings as Data Source: https://cyclopts.readthedocs.io/en/stable/api Explains how to enable JSON parsing for dictionary-like parameters. When enabled, Cyclopts will automatically parse JSON strings if the parameter is a keyword option, dataclass-like, and the token starts with '{'. ```python json_dict _: bool | None_ _ = None_ # Allow for the parsing of json-dict-strings as data. If `None` (default behavior), acts like `True`, **unless** the annotated type is union'd with `str`. When `True`, data will be parsed as json if the following conditions are met: # 1. The parameter is specified as a keyword option; e.g. `--movie`. # 2. The referenced parameter is dataclass-like. # 3. The first character of the token is a `{`. ``` -------------------------------- ### Negative Flag for Optional Parameters (`negative_none`) Source: https://cyclopts.readthedocs.io/en/stable/api Shows how to configure a prefix for negative flags that set optional parameters to `None`. The example demonstrates setting `negative_none` at the `App` level, allowing a `--none-{parameter_name}` syntax to explicitly set an optional parameter to `None`, overriding its default value. ```python from pathlib import Path from typing import Annotated from cyclopts import App, Parameter app = App( default_parameter=Parameter(negative_none="none-") ) @app.default def default(path: Path | None = Path("data.bin")): print(f"{path=}") app() ``` -------------------------------- ### Default Help Output in CLI Source: https://cyclopts.readthedocs.io/en/stable/help Demonstrates the standard help screen generated by Cyclopts for a CLI application, showing commands, options, and descriptions. This output is automatically produced when the --help or -h flag is used. ```bash $ my-application --help Usage: my-application COMMAND My application short description. ╭─ Commands ─────────────────────────────────────────────────────────╮ │ foo Foo help string. │ │ bar Bar help string. │ │ --help -h Display this message and exit. │ │ --version Display application version. │ ╰────────────────────────────────────────────────────────────────────╯ ``` -------------------------------- ### Upgrade CLI Application using pipx Source: https://cyclopts.readthedocs.io/en/stable/cookbook/app_upgrade This command demonstrates how to upgrade a Python-based CLI application installed via pipx to its latest stable version. It assumes the package is named 'mypackage'. ```bash $ pipx upgrade mypackage ``` -------------------------------- ### String Type Hint (Python) Source: https://cyclopts.readthedocs.io/en/stable/rules When a parameter is type-hinted as `str`, no special coercion is performed; CLI tokens are treated as native strings. This example shows a basic string parameter. ```python from cyclopts import App app = App() @app.default def default(value: str): print(f"{value=} {type(value)=}") app() ``` -------------------------------- ### Define Custom Help Formatter Protocol (Python) Source: https://cyclopts.readthedocs.io/en/stable/api Defines the protocol for custom help formatters in Cyclopts. Implementations transform a HelpPanel into rendered text. Optional methods for custom rendering of 'usage' and 'description' are provided. Default rendering is used if these methods are not implemented. ```python from rich.console import Console from rich.console import ConsoleOptions from cyclopts.help import HelpPanel class HelpFormatter: def render_usage(self, console: Console, options: ConsoleOptions, usage: Any) -> None: """Render the usage line.""" ... def render_description(self, console: Console, options: ConsoleOptions, description: Any) -> None: """Render the description.""" ... def __call__(self, console : Console, options : ConsoleOptions, panel : HelpPanel) -> None: """Format and render a single help panel.""" pass ```