### Complete Example: CLI Application and Sphinx Docs Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/sphinx_integration.rst A full example demonstrating a Cyclopts CLI application and its corresponding Sphinx documentation setup. ```python from pathlib import Path from typing import Optional from cyclopts import App app = App( name="myapp", help="My awesome CLI application", version="1.0.0" ) @app.command def init(path: Path = Path("."), template: str = "default"): """Initialize a new project. ``` -------------------------------- ### Setup Cyclopts for Development with uv Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/Installation.rst Recommended for development. Clones the repository and installs all extras using uv for dependency management. ```console git clone https://github.com/BrianPugh/cyclopts.git cd cyclopts uv sync --all-extras ``` -------------------------------- ### Console command example Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/api.rst Example of how to invoke a command with specific environment and replica count. ```console $ my-script deploy -e prod -r 5 ``` -------------------------------- ### YAML Configuration Example Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/api.rst Example of configuring Cyclopts to read from a YAML file. ```python app = cyclopts.App(config=cyclopts.config.Yaml("config.yaml")) ``` -------------------------------- ### Install Cyclopts from GitHub Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/Installation.rst Install directly from the GitHub repository to get the latest development version. Ensure you have git installed. ```console python -m pip install git+https://github.com/BrianPugh/cyclopts.git ``` -------------------------------- ### Interactive Shell Command Help Example Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/cookbook/interactive_help.rst Shows how to get help for a specific command ('foo') within the interactive shell. This displays the command's usage, docstring, and parameters. ```console cyclopts> foo --help Usage: interactive-shell-demo.py foo [ARGS] [OPTIONS] Foo Docstring ╭─ Parameters ──────────────────────────────────────────────────╮ │ * P1,--p1 Foo's first parameter. [required] │ ╰───────────────────────────────────────────────────────────────╯ ``` -------------------------------- ### Example: Create User (No Verbose) Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/cookbook/sharing_parameters.rst An example of invoking the 'create' command without the verbose flag. No output is shown from the CLI itself. ```console $ python demo.py create Alice 42 ``` -------------------------------- ### Installing Completion Manually Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/shell_completion.rst Demonstrates how to manually install shell completion for a Cyclopts application using `App.install_completion`. ```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"), ) ``` -------------------------------- ### TOML Configuration Example Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/api.rst Example of configuring Cyclopts to read from a TOML file, specifying root keys for project configuration. ```python app = cyclopts.App(config=cyclopts.config.Toml("pyproject.toml", root_keys=("tool", "myproject"))) ``` -------------------------------- ### Example: Create User (Verbose) Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/cookbook/sharing_parameters.rst An example of invoking the 'create' command with the verbose flag enabled. This shows the 'Creating user' message. ```console $ python demo.py create Alice 42 --verbose ``` -------------------------------- ### Meta App Execution Example Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/meta_app.rst Demonstrates launching the meta-app with user and command arguments. ```console $ my-script --user=Bob foo 3 Hello Bob Looping! 0 Looping! 1 Looping! 2 ``` -------------------------------- ### Command Execution Example Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/api.rst Illustrates the output of running the 'foo' and 'bar' commands, and how the help screen appears. ```console $ my-script foo Running foo. $ my-script bar Running bar. $ my-script --help Usage: scratch.py COMMAND ╭─ Commands ─────────────────────────────────────────────────╮ │ foo │ │ --help -h Display this message and exit. │ │ --version Display application version. │ ╰────────────────────────────────────────────────────────────╯ ``` -------------------------------- ### Install Dependencies with uv Source: https://github.com/brianpugh/cyclopts/blob/main/CONTRIBUTING.md Install all project dependencies, including development extras, using the uv package manager. ```bash uv sync --all-extras ``` -------------------------------- ### Start Server Source: https://github.com/brianpugh/cyclopts/blob/main/tests/__snapshots__/test_docs_snapshots/TestMarkdownSnapshots.test_server_commands_markdown.md Starts the Cyclopts server with configurable options. This command demonstrates Pydantic model support for CLI parameters. ```APIDOC ## POST /server/start ### Description Starts the server with configuration. ### Method POST ### Endpoint /server/start ### Parameters #### Request Body - **server.host** (string) - Optional - Server bind address. *[default: 0.0.0.0]* - **server.port** (integer) - Optional - Server port number. *[default: 8000]* - **server.workers** (integer) - Optional - Number of worker processes. *[default: 4]* - **server.timeout** (number) - Optional - Request timeout in seconds. *[default: 30.0]* - **server.debug** (boolean) - Optional - Enable debug mode. *[default: False]* - **auth.provider** (string) - Optional - Authentication provider type. *[choices: oauth2, jwt, basic, none]* *[default: jwt]* - **auth.token_expiry** (integer) - Optional - Token expiration time in seconds. *[default: 3600]* - **auth.refresh_enabled** (boolean) - Optional - Enable token refresh. *[default: True]* - **auth.allowed_origins** (array of strings) - Optional - List of allowed CORS origins. ### Request Example { "server": { "host": "127.0.0.1", "port": 8080, "workers": 2, "timeout": 60.0, "debug": true }, "auth": { "provider": "oauth2", "token_expiry": 7200, "refresh_enabled": false, "allowed_origins": ["http://localhost:3000"] } } ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example { "message": "Server started successfully." } ``` -------------------------------- ### Cyclopts CLI Execution Example Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/autoregistry.rst This console output demonstrates executing the download command with specific arguments, showing the output from the selected provider function. ```console $ my-script my-bucket my-key local.bin --provider=s3 Downloading data from Amazon. ``` -------------------------------- ### Install Cyclopts with MkDocs Support Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/mkdocs_integration.rst Install the Cyclopts package with the necessary dependencies for MkDocs integration using pip. ```bash pip install cyclopts[mkdocs] ``` -------------------------------- ### Console Example: Alternative Approach Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/cookbook/file_or_stdin_stdout.rst Demonstrates the usage of the alternative approach for handling stdin/stdout with file input. ```console $ echo "hello cyclopts users." > demo.txt $ python scream.py demo.txt ``` -------------------------------- ### Command Help Output Example Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/commands.rst Illustrates the command-line help output generated by Cyclopts, showing registered commands and their associated help strings. ```console $ my-script --help ╭─ Commands ────────────────────────────────────────────────────────────╮ │ bar Help string for bar. │ │ foo Help string for foo. │ │ --help,-h Display this message and exit. │ │ --version Display application version. │ ╰───────────────────────────────────────────────────────────────────────╯ ``` -------------------------------- ### Example Usage with print_non_int_return_int_as_exit_code Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/api.rst Example of initializing an App with a specific result action for CLI applications using console_scripts entry points. ```python from cyclopts import App # For CLI applications with console_scripts entry points app = App(result_action="print_non_int_return_int_as_exit_code") @app.command def greet(name: str) -> str: return f"Hello {name}!" app() ``` -------------------------------- ### Console Example: Default Stdin/Stdout Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/cookbook/file_or_stdin_stdout.rst Shows how to use the default stdin/stdout behavior when arguments are omitted. ```console $ echo "hello cyclopts users." > demo.txt $ python scream.py demo.txt HELLO CYCLOPTS USERS. $ python scream.py demo.txt output.txt && cat output.txt HELLO CYCLOPTS USERS. $ echo "foo" | python scream.py FOO ``` -------------------------------- ### Install from PR Branch with uv Source: https://github.com/brianpugh/cyclopts/blob/main/CONTRIBUTING.md Install Cyclopts directly from a specific branch of a GitHub repository using uv. Useful for testing pull requests. ```bash uv pip install git+https://github.com/BrianPugh/cyclopts.git@branch-name ``` -------------------------------- ### Install Locally from Git Checkout Source: https://github.com/brianpugh/cyclopts/blob/main/CONTRIBUTING.md Clone the repository, checkout a specific branch, and install the package in editable mode. Useful for local development and testing. ```bash git clone https://github.com/BrianPugh/cyclopts.git cd cyclopts git checkout branch-name # Activate your project's virtual environment, then: pip install -e . ``` -------------------------------- ### Install Cyclopts from PyPI Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/Installation.rst Use this command to install the latest stable version of Cyclopts from the Python Package Index. ```console python -m pip install cyclopts ``` -------------------------------- ### TOML Configuration Example - Python Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/config_file.rst Integrate TOML configuration files into your CLI application. This example shows how to use cyclopts.config.Toml to read settings from pyproject.toml, supporting nested keys and parent directory searching. ```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() ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/brianpugh/cyclopts/blob/main/CONTRIBUTING.md Install pre-commit hooks to ensure code quality and consistency before committing changes. ```bash uv run pre-commit install ``` -------------------------------- ### Meta Command Execution Example Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/meta_app.rst Executes a meta command directly, bypassing the default launcher. ```console $ my-script info CLI didn't have to provide --user to call this. ``` -------------------------------- ### Registering Completion Command Programmatically Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/shell_completion.rst Example of adding a `--install-completion` command to your CLI application using `App.register_install_completion_command`. ```python from cyclopts import App app = App(name="myapp") app.register_install_completion_command() # Your commands here... if __name__ == "__main__": app() ``` -------------------------------- ### Start Complex-CLI Server Source: https://github.com/brianpugh/cyclopts/blob/main/tests/__snapshots__/test_docs_snapshots/TestMarkdownSnapshots.test_full_app_markdown.md Use this command to start the server. It supports Pydantic model integration for defining CLI parameters. Ensure all server and authentication parameters are correctly configured. ```console complex-cli server start [OPTIONS] ``` -------------------------------- ### Launch Interactive Shell with Commands Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/cookbook/interactive_help.rst Defines two commands, 'foo' and 'bar', and then launches the interactive shell. This example shows how to set up commands before entering the shell. ```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> ") ``` -------------------------------- ### Import Path Format Examples Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/lazy_loading.rst These examples illustrate the 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") ``` -------------------------------- ### MkDocs Configuration with Cyclopts Plugin Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/mkdocs_integration.rst Example `mkdocs.yml` configuration enabling the Cyclopts plugin for automatic CLI documentation generation. ```yaml site_name: MyApp Documentation site_description: Documentation for MyApp CLI theme: name: readthedocs plugins: - search - cyclopts nav: - Home: index.md - CLI Reference: cli-reference.md - User Guide: guide.md markdown_extensions: - admonition - codehilite - toc: permalink: true ``` -------------------------------- ### Execute Simple Function CLI Source: https://github.com/brianpugh/cyclopts/blob/main/README.md Example of executing the script created with `cyclopts.run()` from the command line, passing an integer argument. ```console $ python start.py 3 Looping! 0 Looping! 1 Looping! 2 ``` -------------------------------- ### Environment Variable Parsing Example Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/api.rst Demonstrates how environment variables are parsed into command-line arguments. Shows the effect of setting environment variables before running the script. ```console $ python my_script.py my-command 1 2 foo=1 bar=2 $ export MY_SCRIPT_MY_COMMAND_FOO=100 $ python my_script.py my-command --bar=2 foo=100 bar=2 $ python my_script.py my-command 1 2 foo=1 bar=2 ``` -------------------------------- ### Cyclopts CLI Application Example Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/mkdocs_integration.rst A Python CLI application using Cyclopts, demonstrating command definitions with type hints and docstrings. ```python from pathlib import Path from typing import Optional from cyclopts import App app = App( name="myapp", help="My awesome CLI application", version="1.0.0" ) @app.command def init(path: Path = Path("."), template: str = "default"): """Initialize a new project. Parameters ---------- path : Path Directory where the project will be created template : str Project template to use """ print(f"Initializing project at {path}") @app.command def build(source: Path, output: Optional[Path] = None, *, minify: bool = False): """Build the project. Parameters ---------- source : Path Source directory output : Path, optional Output directory (defaults to source/dist) minify : bool Minify the output files """ output = output or source / "dist" print(f"Building from {source} to {output}") if __name__ == "__main__": app() ``` -------------------------------- ### Console Input for n_tokens Example Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/parameters.rst Demonstrates the command-line usage for a parameter configured with `n_tokens=1`, showing how a single token is parsed into a custom object. ```console $ my-script --pos 10,20 Position: (10, 20) ``` -------------------------------- ### Console input for key-specified tokens Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/api.rst Example console input demonstrating the use of keys for token parsing. ```console $ python my-script.py --foo.key1=val1 ``` -------------------------------- ### Console Help Output with Groups Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/groups.rst Example of how command and parameter groups are displayed in the console help output. ```console Usage: my-script.py create [OPTIONS] ╭─ Vehicle (choose one) ───────────────────────────────────────────────────────╮ │ --car [default: False] t │ --truck [default: False] t ╰──────────────────────────────────────────────────────────────────────────────╯ ╭─ Engine ─────────────────────────────────────────────────────────────────────╮ │ --hp [default: 200] t │ --cylinders [default: 6] t ╰──────────────────────────────────────────────────────────────────────────────╯ ╭─ Wheels ─────────────────────────────────────────────────────────────────────╮ │ --wheel-diameter [default: 18] t │ --rims,--no-rims [default: False] t ╰──────────────────────────────────────────────────────────────────────────────╯ ``` -------------------------------- ### Console Example: StdioPath Basic Usage Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/cookbook/file_or_stdin_stdout.rst Demonstrates basic usage of `StdioPath` for reading from a file and writing to stdout, and writing to a file. ```console $ echo "hello cyclopts users." > demo.txt $ python scream.py demo.txt - HELLO CYCLOPTS USERS. $ python scream.py demo.txt output.txt && cat output.txt HELLO CYCLOPTS USERS. $ echo "foo" | python scream.py - - FOO ``` -------------------------------- ### TOML Configuration with Search Parents Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/api.rst Example of configuring Cyclopts to read from a TOML file, enabling search in parent directories if the file is not found. ```python app = cyclopts.App(config=cyclopts.config.Toml("pyproject.toml", search_parents=True)) ``` -------------------------------- ### Build Documentation Source: https://github.com/brianpugh/cyclopts/blob/main/CONTRIBUTING.md Navigate to the docs directory and run the make command to build the HTML documentation. ```bash cd docs make html ``` -------------------------------- ### Generating Completion Script Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/shell_completion.rst Example of generating a shell completion script without installing it using `App.generate_completion`. ```python from cyclopts import App app = App(name="myapp") script = app.generate_completion(shell="zsh") print(script) ``` -------------------------------- ### Activating Virtual Environment for `cyclopts run` Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/shell_completion.rst Example of activating a virtual environment and then using `cyclopts run` to enable shell completion for a development script. ```console $ source .venv/bin/activate # or your venv activation method $ cyclopts run myapp.py ``` -------------------------------- ### Build and Serve MkDocs Documentation Source: https://github.com/brianpugh/cyclopts/blob/main/tests/apps/cyclopts-demo/README.md Use `uv run mkdocs build` to build the static documentation. Serve the documentation locally using `uv run mkdocs serve` to preview changes, which will be accessible at http://127.0.0.1:8000. ```bash # Build the documentation uv run mkdocs build ``` ```bash # Serve the documentation locally uv run mkdocs serve # Opens http://127.0.0.1:8000 ``` -------------------------------- ### Get Cyclopts Version Source: https://github.com/brianpugh/cyclopts/blob/main/CONTRIBUTING.md Retrieve the installed version of Cyclopts using a Python one-liner. Useful for reporting issues. ```python python -c "import cyclopts; print(cyclopts.__version__)" ``` -------------------------------- ### Rich Formatted Traceback Setup Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/cookbook/rich_formatted_exceptions.rst This Python script configures Cyclopts to use Rich for enhanced, visually appealing tracebacks. Ensure the Rich library is installed. ```python import sys from cyclopts import App from rich.console import Console from rich.traceback import install as install_rich_traceback error_console = Console(stderr=True) app = App(console=console, error_console=error_console) # Install rich traceback handler using the error console install_rich_traceback(console=error_console) @app.default def main(name: str): print(name + 3) if __name__ == "__main__": app() ``` -------------------------------- ### Custom Converter for File Size Input Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/parameters.rst Example setup for a custom converter to parse file sizes with suffixes like 'MB' or 'GB'. This requires defining a mapping and a conversion function. ```python from cyclopts import App, Parameter, Token from typing import Annotated, Sequence from pathlib import Path app = App() mapping = { "kb": 1024, "mb": 1024 * 1024, "gb": 1024 * 1024 * 1024, } ``` -------------------------------- ### Typer Deployment Application Source: https://github.com/brianpugh/cyclopts/blob/main/README.md A Typer application that mimics the Cyclopts deployment example. It uses Enums for environments and a custom parser for replica values, demonstrating a more verbose setup for similar functionality. ```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() ``` ```console $ my-script deploy --help Usage: my-script deploy [OPTIONS] ENV:{dev|staging|prod} [REPLICAS] Deploy code to an environment. ╭─ Arguments ─────────────────────────────────────────────────────────────────────────────────────╮ │ * env ENV:{dev|staging|prod} Environment to deploy to. [default: None] [required] │ │ replicas [REPLICAS] Number of workers to spin up. [default: 10] │ ╰─────────────────────────────────────────────────────────────────────────────────────────────────╯ ╭─ Options ───────────────────────────────────────────────────────────────────────────────────────╮ │ --help Show this message and exit. │ ╰─────────────────────────────────────────────────────────────────────────────────────────────────╯ $ my-script deploy staging Deploying to staging with 10 replicas. $ my-script deploy staging 7 Deploying to staging with 7 replicas. $ my-script deploy staging performance Deploying to staging with 20 replicas. $ my-script deploy nonexistent-env Usage: my-script.py deploy [OPTIONS] ENV:{dev|staging|prod} [REPLICAS] Try 'my-script.py deploy --help' for help. ╭─ Error ─────────────────────────────────────────────────────────────────────────────────────────╮ │ Invalid value for '[REPLICAS]': nonexistent-env │ ╰─────────────────────────────────────────────────────────────────────────────────────────────────╯ $ my-script --version 0.0.0 ``` -------------------------------- ### Build MkDocs Documentation Source: https://github.com/brianpugh/cyclopts/blob/main/tests/apps/complex-demo/README.md Navigate to the complex-demo directory and run `mkdocs build` to generate the documentation. Use `mkdocs serve` for live development. ```bash cd tests/apps/complex-demo mkdocs build mkdocs serve # For development ``` -------------------------------- ### NumPy Style Docstring Example Source: https://github.com/brianpugh/cyclopts/blob/main/tests/__snapshots__/test_docs_snapshots/TestSphinxDirectiveSnapshots.test_simple_directive_rst.rst Example of a command using NumPy-style docstrings. ```APIDOC ## complex-cli numpy-style NAME [ARGS] ### Description Command with NumPy-style docstring. This command demonstrates NumPy docstring format which is the default for cyclopts. ### Method N/A (CLI Command) ### Endpoint N/A (CLI Command) ### Parameters #### Path Parameters - **NAME** (string) - The name parameter. [**Required**] - **COUNT** (integer) - The count parameter. ### Response #### Success Response (N/A) N/A (CLI Command) ``` -------------------------------- ### Defining Console Scripts in setup.cfg Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/packaging.rst This configuration file demonstrates how to define console script entrypoints for a package using `setup.cfg`. ```cfg # setup.cfg [options.entry_points] console_scripts = my-package = mypackage.__main__:app ``` -------------------------------- ### Install Cyclopts Source: https://github.com/brianpugh/cyclopts/blob/main/README.md Install the Cyclopts package using pip. Requires Python 3.10 or higher. ```console pip install cyclopts ``` -------------------------------- ### Display Create Command Help Page Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/cookbook/sharing_parameters.rst Examine the help page for the 'create' command to see all its parameters, including the shared ones like URL, port, and verbose flags. ```console $ python demo.py create --help ``` -------------------------------- ### Run the CLI Demo Source: https://github.com/brianpugh/cyclopts/blob/main/tests/apps/cyclopts-demo/README.md Navigate to the demo application directory and execute the CLI with the --help flag to view available commands and options. This is useful for manual testing of shell completion and command-line interface features. ```bash cd tests/apps/cyclopts-demo ``` ```bash python cyclopts_demo.py --help ``` ```bash python cyclopts_demo.py files ls --help ``` ```bash python cyclopts_demo.py database migrate --help ``` -------------------------------- ### Running a Cyclopts App via -m Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/packaging.rst Demonstrates how to execute the `__main__.py` script as a module from the command line. ```console $ python -m mypackage World Hello World! ``` -------------------------------- ### Initialize and Run the Cyclopts App Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/cookbook/sharing_parameters.rst Instantiate the Cyclopts App and define the main entry point for the CLI application. This allows the commands to be registered and executed. ```python if __name__ == "__main__": app() ``` -------------------------------- ### Setting App-Level Help Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/help.rst Illustrates setting help strings at the application level using the 'help' argument during App initialization. This is used when decorator-level help is not specified. ```python 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.") ``` -------------------------------- ### Add Snapshot Test Example Source: https://github.com/brianpugh/cyclopts/blob/main/tests/README.md Example of adding a new snapshot test for a feature, including generating markdown documentation and asserting against a snapshot. ```python def test_my_new_feature(self, ensure_complex_demo_importable, snapshot): """Snapshot test for my new feature.""" from complex_app import app from cyclopts.docs.markdown import generate_markdown_docs markdown = generate_markdown_docs(app, my_new_option=True) assert markdown == snapshot ``` -------------------------------- ### Basic App with Rich Help Format Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/help.rst Initialize an App with `help_format='rich'` to enable Rich markup for help messages. Docstrings will be rendered with Rich formatting. ```python from cyclopts import App app = App(help_format="rich") @app.default def default(): """Rich can display colors like [red]red[/red] easily. However, I cannot be bothered to figure out how to show that in documentation. """ app() ``` -------------------------------- ### Interactive Shell Root Help Example Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/cookbook/interactive_help.rst Illustrates the default behavior of the '--help' flag within the interactive shell when no specific command is selected. It shows the application's commands and global options. ```console $ python interactive-shell-demo.py Interactive shell. Press Ctrl-D to exit. cyclopts> --help Usage: interactive-shell-demo.py COMMAND ╭─ Parameters ──────────────────────────────────────────────────╮ │ --version Display application version. │ │ --help -h Display this message and exit. │ ╰───────────────────────────────────────────────────────────────╯ ╭─ Commands ────────────────────────────────────────────────────╮ │ bar Bar Docstring. │ │ foo Foo Docstring. │ ╰───────────────────────────────────────────────────────────────╯ ``` -------------------------------- ### Defining Console Scripts in setup.py Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/packaging.rst This Python code snippet shows how to define console script entrypoints for a package using `setuptools` in a `setup.py` file. ```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__:app", ], }, ) ``` -------------------------------- ### Install from PR Branch with pip Source: https://github.com/brianpugh/cyclopts/blob/main/CONTRIBUTING.md Install Cyclopts directly from a specific branch of a GitHub repository using pip. Useful for testing pull requests. ```bash pip install git+https://github.com/BrianPugh/cyclopts.git@branch-name ``` -------------------------------- ### TOML Configuration Example - TOML Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/config_file.rst Example TOML configuration for the character-counter CLI tool. This defines the default character for the 'count' command within the 'tool.character-counter' namespace. ```toml [tool.character-counter.count] character = "t" ``` -------------------------------- ### Basic CLI Argument Parsing with Cyclopts Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/rules.rst Demonstrates how to define a simple command-line interface using Cyclopts. This example shows how to set up a program that accepts a single string argument. ```python from cyclopts import App app = App() @app.command() def main(user: str): print(f"Hello, {user}!") if __name__ == "__main__": app.run() ``` -------------------------------- ### Verbose Parameter Parsing Example Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/default_parameter.rst This example shows how a parameter prefixed with an underscore can still be parsed if `parse=True` is explicitly set in its annotation, overriding the default behavior for underscored parameters. ```python def main(name: str, *, _verbose: Annotated[bool, Parameter(parse=True)] = False): """_verbose IS parsed despite the underscore prefix""" ``` -------------------------------- ### JSON Dict Parsing Example with Default Value Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/user_classes.rst Demonstrates parsing a dataclass with a default value from a JSON string. This example shows how to provide all fields, including the one with a default, via JSON. ```console $ movie-manager add --movie '{"title": "Mad Max: Fury Road", "year": 2015, "rating": 8.1}' Adding: Movie(title='Mad Max: Fury Road', year=2015, rating=8.1) $ movie-manager add --movie '{"title": "Furiosa", "year": 2024}' Adding: Movie(title='Furiosa', year=2024, rating=8.0) ``` -------------------------------- ### complex-cli server start Source: https://github.com/brianpugh/cyclopts/blob/main/tests/__snapshots__/test_docs_snapshots/TestMarkdownSnapshots.test_full_app_markdown.md Starts the server with specified configuration options. This command demonstrates Pydantic model support for CLI parameters, allowing detailed control over server host, port, workers, timeouts, and authentication settings. ```APIDOC ## complex-cli server start ### Description Starts the server with configuration. Demonstrates Pydantic model support for CLI parameters. ### Method Not Applicable (CLI Command) ### Endpoint Not Applicable (CLI Command) ### Parameters #### Global Options * `--verbose, -v` (integer) - Optional - Verbosity level (-v, -vv, -vvv). [default: 0] * `--quiet, --no-quiet, -q` (boolean) - Optional - Suppress non-essential output. [default: False] * `--log-level` (string) - Optional - Logging level. [choices: debug, info, warning, error, critical] [default: info] * `--no-color, --no-no-color` (boolean) - Optional - Disable colored output. [default: False] #### Server Parameters * `--server.host` (string) - Optional - Server bind address. [default: 0.0.0.0] * `--server.port` (integer) - Optional - Server port number. [default: 8000] * `--server.workers` (integer) - Optional - Number of worker processes. [default: 4] * `--server.timeout` (float) - Optional - Request timeout in seconds. [default: 30.0] * `--server.debug, --server.no-debug` (boolean) - Optional - Enable debug mode. [default: False] #### Authentication Parameters * `--auth.provider` (string) - Optional - Authentication provider type. [choices: oauth2, jwt, basic, none] [default: jwt] * `--auth.token-expiry` (integer) - Optional - Token expiration time in seconds. [default: 3600] * `--auth.refresh-enabled, --auth.no-refresh-enabled` (boolean) - Optional - Enable token refresh. [default: True] * `--auth.allowed-origins, --auth.empty-allowed-origins` (list) - Optional - List of allowed CORS origins. ### Request Example ```bash complex-cli server start --server.port 8080 --auth.provider none ``` ### Response Not Applicable (CLI Command) ``` -------------------------------- ### Configure Environment Variables with Prefix Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/api.rst Set up an application to read configuration from environment variables, using a specified prefix. This example shows how to define a prefix for environment variable lookups. ```python import cyclopts app = cyclopts.App(config=cyclopts.config.Env("MY_SCRIPT_")) @app.command def my_command(foo, bar): print(f"{foo=} {bar=}") app() ``` -------------------------------- ### Classmethod validator example Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/api.rst Illustrates using a classmethod as a validator, referencing it by name. ```python @Parameter(name="*", validator="validate") @dataclass class TextStyle: color: str bold: bool = False italic: bool = False @classmethod def validate(cls, value): if value.bold and value.italic: raise ValueError("Cannot use both --bold and --italic together.") ``` -------------------------------- ### Classmethod converter example Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/api.rst Demonstrates using a classmethod as a converter, referencing it by name. ```python @Parameter(converter="from_env") class Config: @Parameter(n_tokens=1, accepts_keys=False) @classmethod def from_env(cls, tokens): env = tokens[0].value configs = {"dev": ("localhost", 8080), "prod": ("api.example.com", 443)} return cls(*configs[env]) ``` -------------------------------- ### Display Root Help Page Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/cookbook/sharing_parameters.rst View the main help page for the CLI application to see the available commands and their descriptions. ```console $ python demo.py --help ``` -------------------------------- ### Server Management API Source: https://github.com/brianpugh/cyclopts/blob/main/tests/__snapshots__/test_docs_snapshots/TestSphinxDirectiveSnapshots.test_simple_directive_rst.rst Manage the server lifecycle including starting, stopping, and restarting. ```APIDOC ## complex-cli server start [OPTIONS] ### Description Start the server with configuration. Demonstrates Pydantic model support for CLI parameters. ### Method N/A (CLI Command) ### Endpoint N/A (CLI Command) ### Parameters #### Query Parameters - **--server.host** (string) - Server bind address. [Default: "0.0.0.0"] - **--server.port** (integer) - Server port number. [Default: 8000] - **--server.workers** (integer) - Number of worker processes. [Default: 4] - **--server.timeout** (float) - Request timeout in seconds. [Default: 30.0] - **--server.debug** (boolean) - Enable debug mode. [Default: False] - **--auth.provider** (string) - Authentication provider type. [Choices: "oauth2", "jwt", "basic", "none", Default: "jwt"] - **--auth.token-expiry** (integer) - Token expiration time in seconds. [Default: 3600] - **--auth.refresh-enabled** (boolean) - Enable token refresh. [Default: True] - **--auth.allowed-origins** (list of strings) - List of allowed CORS origins. ### Response #### Success Response (N/A) N/A (CLI Command) ``` ```APIDOC ## complex-cli server stop [OPTIONS] ### Description Stop the server. ### Method N/A (CLI Command) ### Endpoint N/A (CLI Command) ### Parameters #### Query Parameters - **--graceful** (boolean) - Perform graceful shutdown. [Default: True] - **--timeout** (integer) - Shutdown timeout in seconds. [Default: 30] - **--force** (boolean) - Force immediate shutdown. [Default: False] ### Response #### Success Response (N/A) N/A (CLI Command) ``` ```APIDOC ## complex-cli server restart [ARGS] ### Description Restart the server. ### Method N/A (CLI Command) ### Endpoint N/A (CLI Command) ### Parameters #### Path Parameters - **ROLLING** (boolean) - Perform rolling restart (zero downtime). [Default: False] - **DELAY** (integer) - Delay between worker restarts in seconds. [Default: 5] ### Response #### Success Response (N/A) N/A (CLI Command) ``` -------------------------------- ### Custom tuple converter example Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/api.rst Demonstrates a custom converter for a tuple of integers, doubling their values. ```python from cyclopts import App, Parameter from typing import Annotated app = App() def converter(type_, tokens): assert type_ == tuple[int, int] return tuple(2 * int(x.value) for x in tokens) @app.default def main(coordinates: Annotated[tuple[int, int], Parameter(converter=converter)]): print(f"{coordinates=}") app() ``` -------------------------------- ### StdioPath Subclassing - Simple Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/api.rst Example of subclassing StdioPath to use a different trigger string for stdio behavior. ```python from cyclopts.types import StdioPath # Simple: different trigger string class StdinPath(StdioPath): STDIO_STRING = "STDIN" class StdoutPath(StdioPath): STDIO_STRING = "STDOUT" ``` -------------------------------- ### Command Line Invocation for Configuration Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/api.rst Demonstrates how commands are used as keys to access configuration values. This example shows how a CLI command maps to a configuration lookup path. ```console $ python my-script.py my-command ``` -------------------------------- ### Console input for custom tuple converter Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/api.rst Example console input to trigger the custom tuple converter. ```console $ python my-script.py 7 12 ``` -------------------------------- ### Calling App with String and List Inputs Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/app_calling.rst Demonstrates how to explicitly pass input arguments to the app as a single string or a list of strings. ```python app("foo 1 2 3") # 6 app(["foo", "1", "2", "3"]) # 6 ``` -------------------------------- ### Organizing Commands with Groups Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/groups.rst Demonstrates how to use groups to organize commands, including changing the default group for '--help' and '--version'. ```python from cyclopts import App app = App() # Change the group of "--help" and "--version" to the implicitly created "Admin" group. app["--help"].group = "Admin" app["--version"].group = "Admin" @app.command(group="Admin") def info(): """Print debugging system information.""" print("Displaying system info.") @app.command def download(path, url): """Download a file.""" print(f"Downloading {url} to {path}.") @app.command def upload(path, url): """Upload a file.""" print(f"Downloading {url} to {path}.") app() ``` -------------------------------- ### Run Pytest Command Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/cookbook/unit_testing.rst Example of running pytest on the test file to execute the defined unit tests. ```console $ pytest test.py ``` -------------------------------- ### Show Application Information Source: https://github.com/brianpugh/cyclopts/blob/main/tests/__snapshots__/test_docs_snapshots/TestMkDocsDirectiveSnapshots.test_simple_directive_output.md Command to display general application information. ```console complex-cli info [ARGS] ``` -------------------------------- ### Register Commands Using Lazy Loading Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/lazy_loading.rst This example demonstrates lazy loading by registering commands using import path strings. Modules are only loaded when the commands are actually executed, improving startup performance. ```python from cyclopts import App app = App() user_app = App(name="user") # No imports! Modules loaded only when commands execute user_app.command("myapp.commands.users:create") user_app.command("myapp.commands.users:delete") user_app.command("myapp.commands.users:list_users", name="list") app.command(user_app) ``` -------------------------------- ### Pytest Test Session Output Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/cookbook/unit_testing.rst Example output from a successful pytest session, indicating that one test passed. ```console ============================== test session starts ============================== platform darwin -- Python 3.13.0, pytest-8.3.4, pluggy-1.5.0 rootdir: /cyclopts-demo configfile: pyproject.toml plugins: cov-6.0.0, anyio-4.8.0, mock-3.14.0 collected 1 item test.py . [100%] =============================== 1 passed in 0.05s =============================== ``` -------------------------------- ### Custom Error Formatting Example Output Source: https://github.com/brianpugh/cyclopts/blob/main/docs/source/app_calling.rst Illustrates the output when using the custom error formatter with invalid input. ```text $ my-app foo error: Invalid value for VALUE: unable to convert "foo" into int. ```