Skip to content

Commit

Permalink
added support for coroutines
Browse files Browse the repository at this point in the history
  • Loading branch information
dantownsend committed Apr 22, 2020
1 parent beff809 commit 3818864
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 8 deletions.
34 changes: 27 additions & 7 deletions docs/src/cli.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,39 @@ You can register as many functions as you like with the `CLI` instance.

.. code-block:: python
from targ import CLI
from targ import CLI
def add(a: int, b: int):
print(a + b)
def add(a: int, b: int):
print(a + b)
def subtract(a: int, b: int):
print(a - b)
def subtract(a: int, b: int):
print(a - b)
if __name__ == "__main__":
cli = CLI()
cli.register(add)
cli.register(subtract)
cli.run()
You can also register coroutines, as well as normal functions:

.. code-block:: python
import asyncio
from targ import CLI
async def timer(seconds: int):
print(f"Sleeping for {seconds}")
await asyncio.sleep(seconds)
print("Finished")
if __name__ == "__main__":
cli = CLI()
cli.register(add)
cli.register(subtract)
cli.register(timer)
cli.run()
15 changes: 15 additions & 0 deletions example_script.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import asyncio

from targ import CLI


Expand Down Expand Up @@ -77,6 +79,18 @@ def create(username: str):
print(f"Creating {username}")


async def timer(seconds: int):
"""
Countdown for a number of seconds.
:param seconds:
The number of seconds to countdown.
"""
print(f"Sleeping for {seconds}")
await asyncio.sleep(seconds)
print("Finished")


if __name__ == "__main__":
cli = CLI()
cli.register(say_hello)
Expand All @@ -85,4 +99,5 @@ def create(username: str):
cli.register(print_pi)
cli.register(compound_interest)
cli.register(create, group_name="user")
cli.register(timer)
cli.run()
6 changes: 5 additions & 1 deletion targ/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
from functools import cached_property
import inspect
Expand Down Expand Up @@ -160,7 +161,10 @@ def call_with(self, arg_class: Arguments):
if callable(annotation):
kwargs[kwarg_key] = annotation(arg)

self.command(**kwargs)
if inspect.iscoroutinefunction(self.command):
asyncio.run(self.command(**kwargs))
else:
self.command(**kwargs)


@dataclass
Expand Down

0 comments on commit 3818864

Please sign in to comment.