| 1 |
.. _Command Chaining: |
| 2 |
|
| 3 |
================ |
| 4 |
Command Chaining |
| 5 |
================ |
| 6 |
|
| 7 |
Cyclopts does not natively support command chaining. |
| 8 |
This is because Cyclopts opted for more flexible and robust CLI parsing, rather than a compromised, inconsistent parsing experience. |
| 9 |
With that said, Cyclopts gives you the tools to create your own command chaining experience. |
| 10 |
In this example, we will use a special delimiter token (e.g. ``"AND"``) to separate commands. |
| 11 |
|
| 12 |
.. code-block:: python |
| 13 |
|
| 14 |
import itertools |
| 15 |
from cyclopts import App, Parameter |
| 16 |
from typing import Annotated |
| 17 |
|
| 18 |
app = App() |
| 19 |
|
| 20 |
@app.command |
| 21 |
def foo(val: int): |
| 22 |
print(f"FOO {val=}") |
| 23 |
|
| 24 |
@app.command |
| 25 |
def bar(flag: bool): |
| 26 |
print(f"BAR {flag=}") |
| 27 |
|
| 28 |
@app.meta.default |
| 29 |
def main(*tokens: Annotated[str, Parameter(show=False, allow_leading_hyphen=True)]): |
| 30 |
# tokens is ``["foo", "123", "AND", "foo", "456", "AND", "bar", "--flag"]`` |
| 31 |
delimiter = "AND" |
| 32 |
|
| 33 |
groups = [list(group) for key, group in itertools.groupby(tokens, lambda x: x == delimiter) if not key] or [[]] |
| 34 |
# groups is ``[['foo', '123'], ['foo', '456'], ['bar', '--flag']]`` |
| 35 |
|
| 36 |
for group in groups: |
| 37 |
# Execute each group |
| 38 |
app(group) |
| 39 |
|
| 40 |
if __name__ == "__main__": |
| 41 |
app.meta(["foo", "123", "AND", "foo", "456", "AND", "bar", "--flag"]) |
| 42 |
# FOO val=123 |
| 43 |
# FOO val=456 |
| 44 |
# BAR flag=True |