summaryrefslogtreecommitdiffstats
path: root/examples/progress-bar
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-05-04 17:35:20 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-05-04 17:35:20 +0000
commite106bf94eff07d9a59771d9ccc4406421e18ab64 (patch)
treeedb6545500e39df9c67aa918a6125bffc8ec1aee /examples/progress-bar
parentInitial commit. (diff)
downloadprompt-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')
-rwxr-xr-xexamples/progress-bar/a-lot-of-parallel-tasks.py65
-rwxr-xr-xexamples/progress-bar/colored-title-and-label.py22
-rwxr-xr-xexamples/progress-bar/custom-key-bindings.py51
-rwxr-xr-xexamples/progress-bar/many-parallel-tasks.py46
-rwxr-xr-xexamples/progress-bar/nested-progress-bars.py23
-rwxr-xr-xexamples/progress-bar/scrolling-task-name.py23
-rwxr-xr-xexamples/progress-bar/simple-progress-bar.py18
-rwxr-xr-xexamples/progress-bar/styled-1.py36
-rwxr-xr-xexamples/progress-bar/styled-2.py50
-rwxr-xr-xexamples/progress-bar/styled-apt-get-install.py38
-rwxr-xr-xexamples/progress-bar/styled-rainbow.py35
-rwxr-xr-xexamples/progress-bar/styled-tqdm-1.py40
-rwxr-xr-xexamples/progress-bar/styled-tqdm-2.py38
-rwxr-xr-xexamples/progress-bar/two-tasks.py39
-rwxr-xr-xexamples/progress-bar/unknown-length.py26
15 files changed, 550 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()
diff --git a/examples/progress-bar/colored-title-and-label.py b/examples/progress-bar/colored-title-and-label.py
new file mode 100755
index 0000000..0b5e73a
--- /dev/null
+++ b/examples/progress-bar/colored-title-and-label.py
@@ -0,0 +1,22 @@
+#!/usr/bin/env python
+"""
+A progress bar that displays a formatted title above the progress bar and has a
+colored label.
+"""
+import time
+
+from prompt_toolkit.formatted_text import HTML
+from prompt_toolkit.shortcuts import ProgressBar
+
+
+def main():
+ title = HTML('Downloading <style bg="yellow" fg="black">4 files...</style>')
+ label = HTML("<ansired>some file</ansired>: ")
+
+ with ProgressBar(title=title) as pb:
+ for i in pb(range(800), label=label):
+ time.sleep(0.01)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/progress-bar/custom-key-bindings.py b/examples/progress-bar/custom-key-bindings.py
new file mode 100755
index 0000000..f700811
--- /dev/null
+++ b/examples/progress-bar/custom-key-bindings.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+"""
+A very simple progress bar which keep track of the progress as we consume an
+iterator.
+"""
+import os
+import signal
+import time
+
+from prompt_toolkit import HTML
+from prompt_toolkit.key_binding import KeyBindings
+from prompt_toolkit.patch_stdout import patch_stdout
+from prompt_toolkit.shortcuts import ProgressBar
+
+
+def main():
+ bottom_toolbar = HTML(
+ ' <b>[f]</b> Print "f" <b>[q]</b> Abort <b>[x]</b> Send Control-C.'
+ )
+
+ # Create custom key bindings first.
+ kb = KeyBindings()
+ cancel = [False]
+
+ @kb.add("f")
+ def _(event):
+ print("You pressed `f`.")
+
+ @kb.add("q")
+ def _(event):
+ "Quit by setting cancel flag."
+ cancel[0] = True
+
+ @kb.add("x")
+ def _(event):
+ "Quit by sending SIGINT to the main thread."
+ os.kill(os.getpid(), signal.SIGINT)
+
+ # Use `patch_stdout`, to make sure that prints go above the
+ # application.
+ with patch_stdout():
+ with ProgressBar(key_bindings=kb, bottom_toolbar=bottom_toolbar) as pb:
+ for i in pb(range(800)):
+ time.sleep(0.01)
+
+ if cancel[0]:
+ break
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/progress-bar/many-parallel-tasks.py b/examples/progress-bar/many-parallel-tasks.py
new file mode 100755
index 0000000..dc34ef2
--- /dev/null
+++ b/examples/progress-bar/many-parallel-tasks.py
@@ -0,0 +1,46 @@
+#!/usr/bin/env python
+"""
+More complex demonstration of what's possible with the progress bar.
+"""
+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):
+ for i in pb(range(total), label=label):
+ time.sleep(sleep_time)
+
+ threads = [
+ threading.Thread(target=run_task, args=("First task", 50, 0.1)),
+ threading.Thread(target=run_task, args=("Second task", 100, 0.1)),
+ threading.Thread(target=run_task, args=("Third task", 8, 3)),
+ threading.Thread(target=run_task, args=("Fourth task", 200, 0.1)),
+ threading.Thread(target=run_task, args=("Fifth task", 40, 0.2)),
+ threading.Thread(target=run_task, args=("Sixth task", 220, 0.1)),
+ threading.Thread(target=run_task, args=("Seventh task", 85, 0.05)),
+ threading.Thread(target=run_task, args=("Eight task", 200, 0.05)),
+ ]
+
+ 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()
diff --git a/examples/progress-bar/nested-progress-bars.py b/examples/progress-bar/nested-progress-bars.py
new file mode 100755
index 0000000..a585ca1
--- /dev/null
+++ b/examples/progress-bar/nested-progress-bars.py
@@ -0,0 +1,23 @@
+#!/usr/bin/env python
+"""
+Example of nested progress bars.
+"""
+import time
+
+from prompt_toolkit import HTML
+from prompt_toolkit.shortcuts import ProgressBar
+
+
+def main():
+ with ProgressBar(
+ title=HTML('<b fg="#aa00ff">Nested progress bars</b>'),
+ bottom_toolbar=HTML(" <b>[Control-L]</b> clear <b>[Control-C]</b> abort"),
+ ) as pb:
+
+ for i in pb(range(6), label="Main task"):
+ for j in pb(range(200), label=f"Subtask <{i + 1}>", remove_when_done=True):
+ time.sleep(0.01)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/progress-bar/scrolling-task-name.py b/examples/progress-bar/scrolling-task-name.py
new file mode 100755
index 0000000..bce155f
--- /dev/null
+++ b/examples/progress-bar/scrolling-task-name.py
@@ -0,0 +1,23 @@
+#!/usr/bin/env python
+"""
+A very simple progress bar where the name of the task scrolls, because it's too long.
+iterator.
+"""
+import time
+
+from prompt_toolkit.shortcuts import ProgressBar
+
+
+def main():
+ with ProgressBar(
+ title="Scrolling task name (make sure the window is not too big)."
+ ) as pb:
+ for i in pb(
+ range(800),
+ label="This is a very very very long task that requires horizontal scrolling ...",
+ ):
+ time.sleep(0.01)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/progress-bar/simple-progress-bar.py b/examples/progress-bar/simple-progress-bar.py
new file mode 100755
index 0000000..c8776e5
--- /dev/null
+++ b/examples/progress-bar/simple-progress-bar.py
@@ -0,0 +1,18 @@
+#!/usr/bin/env python
+"""
+A very simple progress bar which keep track of the progress as we consume an
+iterator.
+"""
+import time
+
+from prompt_toolkit.shortcuts import ProgressBar
+
+
+def main():
+ with ProgressBar() as pb:
+ for i in pb(range(800)):
+ time.sleep(0.01)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/progress-bar/styled-1.py b/examples/progress-bar/styled-1.py
new file mode 100755
index 0000000..d972e55
--- /dev/null
+++ b/examples/progress-bar/styled-1.py
@@ -0,0 +1,36 @@
+#!/usr/bin/env python
+"""
+A very simple progress bar which keep track of the progress as we consume an
+iterator.
+"""
+import time
+
+from prompt_toolkit.shortcuts import ProgressBar
+from prompt_toolkit.styles import Style
+
+style = Style.from_dict(
+ {
+ "title": "#4444ff underline",
+ "label": "#ff4400 bold",
+ "percentage": "#00ff00",
+ "bar-a": "bg:#00ff00 #004400",
+ "bar-b": "bg:#00ff00 #000000",
+ "bar-c": "#000000 underline",
+ "current": "#448844",
+ "total": "#448844",
+ "time-elapsed": "#444488",
+ "time-left": "bg:#88ff88 #000000",
+ }
+)
+
+
+def main():
+ with ProgressBar(
+ style=style, title="Progress bar example with custom styling."
+ ) as pb:
+ for i in pb(range(1600), label="Downloading..."):
+ time.sleep(0.01)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/progress-bar/styled-2.py b/examples/progress-bar/styled-2.py
new file mode 100755
index 0000000..eb2c479
--- /dev/null
+++ b/examples/progress-bar/styled-2.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+"""
+A very simple progress bar which keep track of the progress as we consume an
+iterator.
+"""
+import time
+
+from prompt_toolkit.formatted_text import HTML
+from prompt_toolkit.shortcuts import ProgressBar
+from prompt_toolkit.shortcuts.progress_bar import formatters
+from prompt_toolkit.styles import Style
+
+style = Style.from_dict(
+ {
+ "progressbar title": "#0000ff",
+ "item-title": "#ff4400 underline",
+ "percentage": "#00ff00",
+ "bar-a": "bg:#00ff00 #004400",
+ "bar-b": "bg:#00ff00 #000000",
+ "bar-c": "bg:#000000 #000000",
+ "tildes": "#444488",
+ "time-left": "bg:#88ff88 #ffffff",
+ "spinning-wheel": "bg:#ffff00 #000000",
+ }
+)
+
+
+def main():
+ custom_formatters = [
+ formatters.Label(),
+ formatters.Text(" "),
+ formatters.SpinningWheel(),
+ formatters.Text(" "),
+ formatters.Text(HTML("<tildes>~~~</tildes>")),
+ formatters.Bar(sym_a="#", sym_b="#", sym_c="."),
+ formatters.Text(" left: "),
+ formatters.TimeLeft(),
+ ]
+ with ProgressBar(
+ title="Progress bar example with custom formatter.",
+ formatters=custom_formatters,
+ style=style,
+ ) as pb:
+
+ for i in pb(range(20), label="Downloading..."):
+ time.sleep(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/progress-bar/styled-apt-get-install.py b/examples/progress-bar/styled-apt-get-install.py
new file mode 100755
index 0000000..bafe70b
--- /dev/null
+++ b/examples/progress-bar/styled-apt-get-install.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python
+"""
+Styled just like an apt-get installation.
+"""
+import time
+
+from prompt_toolkit.shortcuts import ProgressBar
+from prompt_toolkit.shortcuts.progress_bar import formatters
+from prompt_toolkit.styles import Style
+
+style = Style.from_dict(
+ {
+ "label": "bg:#ffff00 #000000",
+ "percentage": "bg:#ffff00 #000000",
+ "current": "#448844",
+ "bar": "",
+ }
+)
+
+
+def main():
+ custom_formatters = [
+ formatters.Label(),
+ formatters.Text(": [", style="class:percentage"),
+ formatters.Percentage(),
+ formatters.Text("]", style="class:percentage"),
+ formatters.Text(" "),
+ formatters.Bar(sym_a="#", sym_b="#", sym_c="."),
+ formatters.Text(" "),
+ ]
+
+ with ProgressBar(style=style, formatters=custom_formatters) as pb:
+ for i in pb(range(1600), label="Installing"):
+ time.sleep(0.01)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/progress-bar/styled-rainbow.py b/examples/progress-bar/styled-rainbow.py
new file mode 100755
index 0000000..e45a916
--- /dev/null
+++ b/examples/progress-bar/styled-rainbow.py
@@ -0,0 +1,35 @@
+#!/usr/bin/env python
+"""
+A simple progress bar, visualised with rainbow colors (for fun).
+"""
+import time
+
+from prompt_toolkit.output import ColorDepth
+from prompt_toolkit.shortcuts import ProgressBar
+from prompt_toolkit.shortcuts.progress_bar import formatters
+from prompt_toolkit.shortcuts.prompt import confirm
+
+
+def main():
+ true_color = confirm("Yes true colors? (y/n) ")
+
+ custom_formatters = [
+ formatters.Label(),
+ formatters.Text(" "),
+ formatters.Rainbow(formatters.Bar()),
+ formatters.Text(" left: "),
+ formatters.Rainbow(formatters.TimeLeft()),
+ ]
+
+ if true_color:
+ color_depth = ColorDepth.DEPTH_24_BIT
+ else:
+ color_depth = ColorDepth.DEPTH_8_BIT
+
+ with ProgressBar(formatters=custom_formatters, color_depth=color_depth) as pb:
+ for i in pb(range(20), label="Downloading..."):
+ time.sleep(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/progress-bar/styled-tqdm-1.py b/examples/progress-bar/styled-tqdm-1.py
new file mode 100755
index 0000000..9484ac0
--- /dev/null
+++ b/examples/progress-bar/styled-tqdm-1.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+"""
+Styled similar to tqdm, another progress bar implementation in Python.
+
+See: https://github.com/noamraph/tqdm
+"""
+import time
+
+from prompt_toolkit.shortcuts import ProgressBar
+from prompt_toolkit.shortcuts.progress_bar import formatters
+from prompt_toolkit.styles import Style
+
+style = Style.from_dict({"": "cyan"})
+
+
+def main():
+ custom_formatters = [
+ formatters.Label(suffix=": "),
+ formatters.Bar(start="|", end="|", sym_a="#", sym_b="#", sym_c="-"),
+ formatters.Text(" "),
+ formatters.Progress(),
+ formatters.Text(" "),
+ formatters.Percentage(),
+ formatters.Text(" [elapsed: "),
+ formatters.TimeElapsed(),
+ formatters.Text(" left: "),
+ formatters.TimeLeft(),
+ formatters.Text(", "),
+ formatters.IterationsPerSecond(),
+ formatters.Text(" iters/sec]"),
+ formatters.Text(" "),
+ ]
+
+ with ProgressBar(style=style, formatters=custom_formatters) as pb:
+ for i in pb(range(1600), label="Installing"):
+ time.sleep(0.01)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/progress-bar/styled-tqdm-2.py b/examples/progress-bar/styled-tqdm-2.py
new file mode 100755
index 0000000..0e66e90
--- /dev/null
+++ b/examples/progress-bar/styled-tqdm-2.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python
+"""
+Styled similar to tqdm, another progress bar implementation in Python.
+
+See: https://github.com/noamraph/tqdm
+"""
+import time
+
+from prompt_toolkit.shortcuts import ProgressBar
+from prompt_toolkit.shortcuts.progress_bar import formatters
+from prompt_toolkit.styles import Style
+
+style = Style.from_dict({"bar-a": "reverse"})
+
+
+def main():
+ custom_formatters = [
+ formatters.Label(suffix=": "),
+ formatters.Percentage(),
+ formatters.Bar(start="|", end="|", sym_a=" ", sym_b=" ", sym_c=" "),
+ formatters.Text(" "),
+ formatters.Progress(),
+ formatters.Text(" ["),
+ formatters.TimeElapsed(),
+ formatters.Text("<"),
+ formatters.TimeLeft(),
+ formatters.Text(", "),
+ formatters.IterationsPerSecond(),
+ formatters.Text("it/s]"),
+ ]
+
+ with ProgressBar(style=style, formatters=custom_formatters) as pb:
+ for i in pb(range(1600), label="Installing"):
+ time.sleep(0.01)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/progress-bar/two-tasks.py b/examples/progress-bar/two-tasks.py
new file mode 100755
index 0000000..c78604e
--- /dev/null
+++ b/examples/progress-bar/two-tasks.py
@@ -0,0 +1,39 @@
+#!/usr/bin/env python
+"""
+Two progress bars that run in parallel.
+"""
+import threading
+import time
+
+from prompt_toolkit.shortcuts import ProgressBar
+
+
+def main():
+ with ProgressBar() as pb:
+ # Two parallal tasks.
+ def task_1():
+ for i in pb(range(100)):
+ time.sleep(0.05)
+
+ def task_2():
+ for i in pb(range(150)):
+ time.sleep(0.08)
+
+ # Start threads.
+ t1 = threading.Thread(target=task_1)
+ t2 = threading.Thread(target=task_2)
+ t1.daemon = True
+ t2.daemon = True
+ t1.start()
+ t2.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 [t1, t2]:
+ while t.is_alive():
+ t.join(timeout=0.5)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/progress-bar/unknown-length.py b/examples/progress-bar/unknown-length.py
new file mode 100755
index 0000000..e39ac39
--- /dev/null
+++ b/examples/progress-bar/unknown-length.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python
+"""
+A very simple progress bar which keep track of the progress as we consume an
+iterator.
+"""
+import time
+
+from prompt_toolkit.shortcuts import ProgressBar
+
+
+def data():
+ """
+ A generator that produces items. len() doesn't work here, so the progress
+ bar can't estimate the time it will take.
+ """
+ yield from range(1000)
+
+
+def main():
+ with ProgressBar() as pb:
+ for i in pb(data()):
+ time.sleep(0.1)
+
+
+if __name__ == "__main__":
+ main()