main.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #!/usr/bin/env python3
  2. import asyncio
  3. import time
  4. from concurrent.futures import ProcessPoolExecutor
  5. from multiprocessing import Manager, Queue
  6. from nicegui import app, ui
  7. pool = ProcessPoolExecutor()
  8. def heavy_computation(q: Queue) -> str:
  9. '''Some heavy computation that updates the progress bar through the queue.'''
  10. n = 50
  11. for i in range(n):
  12. # Perform some heavy computation
  13. time.sleep(0.1)
  14. # Update the progress bar through the queue
  15. q.put_nowait(i / n)
  16. return 'Done!'
  17. @ui.page('/')
  18. def main_page():
  19. async def start_computation():
  20. progressbar.visible = True
  21. loop = asyncio.get_running_loop()
  22. result = await loop.run_in_executor(pool, heavy_computation, queue)
  23. ui.notify(result)
  24. progressbar.visible = False
  25. # Create a queue to communicate with the heavy computation process
  26. queue = Manager().Queue()
  27. # Update the progress bar on the main process
  28. ui.timer(0.1, callback=lambda: progressbar.set_value(queue.get() if not queue.empty() else progressbar.value))
  29. # Create the UI
  30. ui.button('compute', on_click=start_computation)
  31. progressbar = ui.linear_progress(value=0).props('instant-feedback')
  32. progressbar.visible = False
  33. # stop the pool when the app is closed; will not cancel any running tasks
  34. app.on_shutdown(pool.shutdown)
  35. ui.run()