diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-04 17:35:20 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-04 17:35:20 +0000 |
commit | e106bf94eff07d9a59771d9ccc4406421e18ab64 (patch) | |
tree | edb6545500e39df9c67aa918a6125bffc8ec1aee /examples/progress-bar/a-lot-of-parallel-tasks.py | |
parent | Initial commit. (diff) | |
download | prompt-toolkit-e106bf94eff07d9a59771d9ccc4406421e18ab64.tar.xz prompt-toolkit-e106bf94eff07d9a59771d9ccc4406421e18ab64.zip |
Adding upstream version 3.0.36.upstream/3.0.36upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'examples/progress-bar/a-lot-of-parallel-tasks.py')
-rwxr-xr-x | examples/progress-bar/a-lot-of-parallel-tasks.py | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/examples/progress-bar/a-lot-of-parallel-tasks.py b/examples/progress-bar/a-lot-of-parallel-tasks.py new file mode 100755 index 0000000..31110ac --- /dev/null +++ b/examples/progress-bar/a-lot-of-parallel-tasks.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +""" +More complex demonstration of what's possible with the progress bar. +""" +import random +import threading +import time + +from prompt_toolkit import HTML +from prompt_toolkit.shortcuts import ProgressBar + + +def main(): + with ProgressBar( + title=HTML("<b>Example of many parallel tasks.</b>"), + bottom_toolbar=HTML("<b>[Control-L]</b> clear <b>[Control-C]</b> abort"), + ) as pb: + + def run_task(label, total, sleep_time): + """Complete a normal run.""" + for i in pb(range(total), label=label): + time.sleep(sleep_time) + + def stop_task(label, total, sleep_time): + """Stop at some random index. + + Breaking out of iteration at some stop index mimics how progress + bars behave in cases where errors are raised. + """ + stop_i = random.randrange(total) + bar = pb(range(total), label=label) + for i in bar: + if stop_i == i: + bar.label = f"{label} BREAK" + break + time.sleep(sleep_time) + + threads = [] + + for i in range(160): + label = "Task %i" % i + total = random.randrange(50, 200) + sleep_time = random.randrange(5, 20) / 100.0 + + threads.append( + threading.Thread( + target=random.choice((run_task, stop_task)), + args=(label, total, sleep_time), + ) + ) + + for t in threads: + t.daemon = True + t.start() + + # Wait for the threads to finish. We use a timeout for the join() call, + # because on Windows, join cannot be interrupted by Control-C or any other + # signal. + for t in threads: + while t.is_alive(): + t.join(timeout=0.5) + + +if __name__ == "__main__": + main() |