-
QuestionI have blocking code which I would like to run using When I run the code below, I get the following error: Is there any way of running blocking code which is located within a Here is a script for reproducing the error based on https://github.com/zauberzeug/nicegui/blob/main/examples/progress/main.py, but #!/usr/bin/env python3
import time
from multiprocessing import Manager, Queue
from nicegui import run, ui
@ui.page('/')
def main_page():
def heavy_computation(q: Queue) -> str:
"""Run some heavy computation that updates the progress bar through the queue."""
n = 50
for i in range(n):
# Perform some heavy computation
time.sleep(0.1)
# Update the progress bar through the queue
q.put_nowait(i / n)
return 'Done!'
async def start_computation():
progressbar.visible = True
result = await run.cpu_bound(heavy_computation, queue)
ui.notify(result)
progressbar.visible = False
# Create a queue to communicate with the heavy computation process
queue = Manager().Queue()
# Update the progress bar on the main process
ui.timer(0.1, callback=lambda: progressbar.set_value(queue.get() if not queue.empty() else progressbar.value))
# Create the UI
ui.button('compute', on_click=start_computation)
progressbar = ui.linear_progress(value=0).props('instant-feedback')
progressbar.visible = False
ui.run() |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
|
Beta Was this translation helpful? Give feedback.
run.cpu_bound
needs to execute the function in a separate process. For this it needs to transfer the whole state of the passed function to the process (which is done with pickle). We typically solve this in our own code by creating static methods (or free functions) which get all the data as simple parameters (eg. no class/ui logic).