1#!/usr/bin/env python
2
3"""Example: run a slow computation on a worker thread and show its progress, its log and its result.
4
5Press :kbd:`Enter` on the button to start the computation and :kbd:`q` to exit.
6The interface keeps answering keys while the worker runs.
7The worker logs each step through :class:`urwid.log_handler.ListWalkerHandler` into a list below the result.
8"""
9
10from __future__ import annotations
11
12import contextlib
13import logging
14import threading
15import time
16
17import urwid
18import urwid.log_handler
19
20STEPS = 20
21logger = logging.getLogger("thread_worker")
22
23
24def compute(loop: urwid.MainLoop, progress: urwid.ProgressBar, status: urwid.Text) -> None:
25 """Sum the squares of 1 to :data:`STEPS` slowly, reporting each step to the loop.
26
27 Runs on the worker thread: widgets are changed only through :meth:`urwid.MainLoop.call_from_thread`,
28 and the log handler hands its records to the loop the same way.
29
30 :param loop: main loop that shows the progress
31 :param progress: bar showing the steps done
32 :param status: text showing the result
33 """
34 total = 0
35 # RuntimeError: the loop stopped, so nothing shows the result any more
36 with contextlib.suppress(RuntimeError):
37 for step in range(1, STEPS + 1):
38 time.sleep(0.2)
39 total += step * step
40 logger.info("step %d of %d: total %d", step, STEPS, total)
41 loop.call_from_thread(progress.set_completion, step)
42 loop.call_from_thread(status.set_text, f"Done: the sum of squares is {total}.")
43
44
45def main() -> None:
46 """Run the example."""
47 status = urwid.Text("Not started.")
48 progress = urwid.ProgressBar("pg normal", "pg complete", done=STEPS)
49 worker: threading.Thread | None = None
50
51 def start(_button: urwid.Button) -> None:
52 """Start the worker, unless it is still running."""
53 nonlocal worker
54 if worker is not None and worker.is_alive():
55 return
56 status.set_text("Working...")
57 progress.set_completion(0)
58 # A daemon thread, so that q does not wait for the computation to finish.
59 worker = threading.Thread(target=compute, args=(loop, progress, status), daemon=True)
60 worker.start()
61
62 def handle_key(key: str | tuple[str, int, int, int]) -> None:
63 """Exit on :kbd:`q`.
64
65 :param key: unhandled key or mouse event
66 :raises urwid.ExitMainLoop: when the user presses :kbd:`q`
67 """
68 if key in {"q", "Q"}:
69 raise urwid.ExitMainLoop
70
71 log: urwid.SimpleFocusDequeWalker[urwid.Text] = urwid.SimpleFocusDequeWalker([], maxlen=100, follow_end=True)
72 body = urwid.Pile(
73 [
74 (urwid.PACK, urwid.Button("Compute", on_press=start)),
75 (urwid.PACK, progress),
76 (urwid.PACK, status),
77 urwid.ListBox(log),
78 ],
79 )
80 loop = urwid.MainLoop(
81 body,
82 palette=[("pg normal", "white", "dark gray"), ("pg complete", "white", "dark blue")],
83 unhandled_input=handle_key,
84 )
85 handler = urwid.log_handler.ListWalkerHandler(log, loop=loop)
86 logger.setLevel(logging.INFO)
87 logger.addHandler(handler)
88 # Shows what was logged before the run started.
89 loop.set_alarm_in(0, lambda _loop, _data: handler.resume())
90 try:
91 loop.run()
92 finally:
93 logger.removeHandler(handler)
94 handler.close()
95
96
97if __name__ == "__main__":
98 main()