printer_asyncio.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import asyncio
  2. from typing import Callable, TypeVar
  3. from wandb.sdk import wandb_setup
  4. from wandb.sdk.lib import asyncio_compat, printer
  5. _T = TypeVar("_T")
  6. def run_async_with_spinner(
  7. spinner_printer: printer.Printer,
  8. text: str,
  9. func: Callable[[], _T],
  10. ) -> _T:
  11. """Run a slow function while displaying a loading icon.
  12. Args:
  13. spinner_printer: The printer to use to display text.
  14. text: The text to display next to the spinner while the function runs.
  15. func: The function to run.
  16. Returns:
  17. The result of func.
  18. """
  19. async def loop_run_with_spinner() -> _T:
  20. async def update_spinner() -> None:
  21. tick = 0
  22. with spinner_printer.dynamic_text() as text_area:
  23. if not text_area:
  24. spinner_printer.display(text)
  25. return
  26. while True:
  27. spinner = spinner_printer.loading_symbol(tick)
  28. text_area.set_text(f"{spinner} {text}")
  29. tick += 1
  30. await asyncio.sleep(0.1)
  31. async with asyncio_compat.cancel_on_exit(update_spinner()):
  32. return await asyncio.get_running_loop().run_in_executor(None, func)
  33. asyncer = wandb_setup.singleton().asyncer
  34. return asyncer.run(loop_run_with_spinner)