blob: f7008119dbfc3df53830c38b0b4d874106e6e295 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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()
|