main.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/usr/bin/env python3
  2. import time
  3. from multiprocessing import Manager, Queue
  4. from nicegui import run, ui
  5. def heavy_computation(q: Queue) -> str:
  6. """Run some heavy computation that updates the progress bar through the queue."""
  7. n = 50
  8. for i in range(n):
  9. # Perform some heavy computation
  10. time.sleep(0.1)
  11. # Update the progress bar through the queue
  12. q.put_nowait(i / n)
  13. return 'Done!'
  14. @ui.page('/')
  15. def main_page():
  16. async def start_computation():
  17. progressbar.visible = True
  18. result = await run.cpu_bound(heavy_computation, queue)
  19. ui.notify(result)
  20. progressbar.visible = False
  21. # Create a queue to communicate with the heavy computation process
  22. queue = Manager().Queue()
  23. # Update the progress bar on the main process
  24. ui.timer(0.1, callback=lambda: progressbar.set_value(queue.get() if not queue.empty() else progressbar.value))
  25. # Create the UI
  26. ui.button('compute', on_click=start_computation)
  27. progressbar = ui.linear_progress(value=0).props('instant-feedback')
  28. progressbar.visible = False
  29. ui.run()