Skip to content

Commit a144fe8

Browse files
committed
Add Radicli.call
1 parent ba3eca3 commit a144fe8

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,20 @@ if __name__ == "__main__":
502502
| -------- | --------------------- | ----------------------------------------------------------------------------------------- |
503503
| `args` | `Optional[List[str]]` | Optional command to pass in. Will be read from `sys.argv` if not set (standard use case). |
504504

505+
#### <kbd>method</kbd> `Radicli.call`
506+
507+
Call a command with args.
508+
509+
```python
510+
command = cli.commands["hello"]
511+
cli.call(command, ["Alex", "--age", "35"])
512+
```
513+
514+
| Argument | Type | Description |
515+
| --------- | --------------------- | ----------------------------------------------------------------------------------------- |
516+
| `command` | `Command` | The command. |
517+
| `args` | `Optional[List[str]]` | Optional command to pass in. Will be read from `sys.argv` if not set (standard use case). |
518+
505519
#### <kbd>method</kbd> `Radicli.parse`
506520

507521
Parse a list of arguments for a given command. Typically internals, but can also be used for testing.

radicli/cli.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from pathlib import Path
77
from contextlib import contextmanager
88
import json
9+
import copy
910

1011
from .parser import ArgumentParser, HelpFormatter
1112
from .util import Arg, ArgparseArg, get_arg, join_strings, format_type, format_table
@@ -249,6 +250,15 @@ def func(*args, **kwargs) -> None:
249250
)
250251
self.commands[name] = dummy
251252

253+
def call(self, command: Command, args: Optional[List[str]] = None) -> None:
254+
"""Call a single command."""
255+
run_args = args if args is not None else [*sys.argv[1:]]
256+
cmd = copy.deepcopy(command)
257+
cmd.name = "" # for nicer display in help text
258+
values = self.parse(run_args, cmd)
259+
with self.handle_errors():
260+
command.func(**values)
261+
252262
def run(self, args: Optional[List[str]] = None) -> None:
253263
"""
254264
Run the CLI. Should typically be used in the __main__.py nested under a

0 commit comments

Comments
 (0)