Skip to content
Myr

Document calling a command as a regular function

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Closes #1054

authored by Kevin Deldycke · committed by Kevin Deldycke · parent b024123 · Browse files · 1 file+43 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+43 added−0 removed

  • other:+43 added−0 removed

1 file+43 added−0 removed

modified:docs/faqs.md+43 added
5 unmodified lines
6```78## General910### Calling a command as a regular function1112I decorated a function with `@click.command()` to make it a CLI. When I import that name and call it from Python, it does not run my function. It parses arguments, prints a usage error and exits the process:1314```pytb15>>> nasa_date_to_iso("2017-090")16Usage: cli [OPTIONS] DATESTR17Try 'cli --help' for help.1819Error: Got unexpected extra arguments (0 1 7 - 0 9 0)20SystemExit: 221```2223#### Answer2425This is not a bug in Click. The decorator replaced the function with a {class}`Command` object. Calling that object runs the Click pipeline, and its argument is the list of command line arguments to parse, not the function's parameters.2627The recommended pattern is to keep a plain function and wrap it with a thin command:2829```python30def nasa_date_to_iso(datestr): ...313233@click.command("nasa_date_to_iso")34@click.argument("datestr")35def nasa_date_to_iso_command(datestr):36 click.echo(nasa_date_to_iso(datestr))37```3839The function stays available as a Python API, and the command adds the CLI on top. Extracting behavior into a shared function used by several entry points is a common refactor.4041If you still want to run the command itself from Python, call it with a list of arguments and `standalone_mode=False` so it returns the result instead of exiting. This runs the Click pipeline, including parsing, validation and callbacks:4243```python44nasa_date_to_iso_command(["2017-090"], standalone_mode=False)45```4647An alternative form is:4849```python50nasa_date_to_iso_command.main(["2017-090"], standalone_mode=False)51```5253### Shell Variable Expansion On Windows5455I have a simple Click app :56
195 unmodified lines