| 1 | import asyncio |
| 2 | import io |
| 3 | import sys |
| 4 | from typing import Callable, Any, Awaitable, Tuple |
| 5 | |
| 6 | def capture_prints_async( |
| 7 | func: Callable[..., Awaitable[Any]], |
| 8 | *args, |
| 9 | **kwargs |
| 10 | ) -> Tuple[Awaitable[Any], Callable[[], str]]: |
| 11 | # Create a StringIO object to capture the output |
| 12 | captured_output = io.StringIO() |
| 13 | original_stdout = sys.stdout |
| 14 | |
| 15 | # Define a function to get the current captured output |
| 16 | def get_current_output() -> str: |
| 17 | return captured_output.getvalue() |
| 18 | |
| 19 | async def wrapped_func() -> Any: |
| 20 | nonlocal captured_output, original_stdout |
| 21 | try: |
| 22 | # Redirect sys.stdout to the StringIO object |
| 23 | sys.stdout = captured_output |
| 24 | # Await the provided function |
| 25 | return await func(*args, **kwargs) |
| 26 | finally: |
| 27 | # Restore the original sys.stdout |
| 28 | sys.stdout = original_stdout |
| 29 | |
| 30 | # Return the wrapped awaitable and the output retriever |
| 31 | return asyncio.create_task(wrapped_func()), get_current_output |