1#!/usr/bin/python 2# -*- coding: utf-8 -*- 3 4from __future__ import absolute_import 5from __future__ import division 6from __future__ import print_function 7from __future__ import unicode_literals 8from __future__ import with_statement 9 10import functools 11import random 12import sys 13import time 14 15import progressbar 16 17examples = [] 18 19 20def example(fn): 21 '''Wrap the examples so they generate readable output''' 22 23 @functools.wraps(fn) 24 def wrapped(*args, **kwargs): 25 try: 26 sys.stdout.write('Running: %s\n' % fn.__name__) 27 fn(*args, **kwargs) 28 sys.stdout.write('\n') 29 except KeyboardInterrupt: 30 sys.stdout.write('\nSkipping example.\n\n') 31 # Sleep a bit to make killing the script easier 32 time.sleep(0.2) 33 34 examples.append(wrapped) 35 return wrapped 36 37 38@example 39def fast_example(): 40 ''' Updates bar really quickly to cause flickering ''' 41 with progressbar.ProgressBar(widgets=[progressbar.Bar()]) as bar: 42 for i in range(100): 43 bar.update(int(i / 10), force=True) 44 45 46@example 47def shortcut_example(): 48 for i in progressbar.progressbar(range(10)): 49 time.sleep(0.1) 50 51 52@example 53def prefixed_shortcut_example(): 54 for i in progressbar.progressbar(range(10), prefix='Hi: '): 55 time.sleep(0.1) 56 57 58@example 59def templated_shortcut_example(): 60 for i in progressbar.progressbar(range(10), suffix='{seconds_elapsed:.1}'): 61 time.sleep(0.1) 62 63 64@example 65def with_example_stdout_redirection(): 66 with progressbar.ProgressBar(max_value=10, redirect_stdout=True) as p: 67 for i in range(10): 68 if i % 3 == 0: 69 print('Some print statement %i' % i) 70 # do something 71 p.update(i) 72 time.sleep(0.1) 73 74 75@example 76def basic_widget_example(): 77 widgets = [progressbar.Percentage(), progressbar.Bar()] 78 bar = progressbar.ProgressBar(widgets=widgets, max_value=10).start() 79 for i in range(10): 80 # do something 81 time.sleep(0.1) 82 bar.update(i + 1) 83 bar.finish() 84 85 86@example 87def color_bar_example(): 88 widgets = [ 89 '\x1b[33mColorful example\x1b[39m', 90 progressbar.Percentage(), 91 progressbar.Bar(marker='\x1b[32m#\x1b[39m'), 92 ] 93 bar = progressbar.ProgressBar(widgets=widgets, max_value=10).start() 94 for i in range(10): 95 # do something 96 time.sleep(0.1) 97 bar.update(i + 1) 98 bar.finish() 99 100 101@example 102def color_bar_animated_marker_example(): 103 widgets = [ 104 # Colored animated marker with colored fill: 105 progressbar.Bar(marker=progressbar.AnimatedMarker( 106 fill='x', 107 # fill='█', 108 fill_wrap='\x1b[32m{}\x1b[39m', 109 marker_wrap='\x1b[31m{}\x1b[39m', 110 )), 111 ] 112 bar = progressbar.ProgressBar(widgets=widgets, max_value=10).start() 113 for i in range(10): 114 # do something 115 time.sleep(0.1) 116 bar.update(i + 1) 117 bar.finish() 118 119 120@example 121def multi_range_bar_example(): 122 markers = [ 123 '\x1b[32m█\x1b[39m', # Done 124 '\x1b[33m#\x1b[39m', # Processing 125 '\x1b[31m.\x1b[39m', # Scheduling 126 ' ' # Not started 127 ] 128 widgets = [progressbar.MultiRangeBar("amounts", markers=markers)] 129 amounts = [0] * (len(markers) - 1) + [25] 130 131 with progressbar.ProgressBar(widgets=widgets, max_value=10).start() as bar: 132 while True: 133 incomplete_items = [ 134 idx 135 for idx, amount in enumerate(amounts) 136 for i in range(amount) 137 if idx != 0 138 ] 139 if not incomplete_items: 140 break 141 which = random.choice(incomplete_items) 142 amounts[which] -= 1 143 amounts[which - 1] += 1 144 145 bar.update(amounts=amounts, force=True) 146 time.sleep(0.02) 147 148 149@example 150def multi_progress_bar_example(left=True): 151 jobs = [ 152 # Each job takes between 1 and 10 steps to complete 153 [0, random.randint(1, 10)] 154 for i in range(25) # 25 jobs total 155 ] 156 157 widgets = [ 158 progressbar.Percentage(), 159 ' ', progressbar.MultiProgressBar('jobs', fill_left=left), 160 ] 161 162 max_value = sum([total for progress, total in jobs]) 163 with progressbar.ProgressBar(widgets=widgets, max_value=max_value) as bar: 164 while True: 165 incomplete_jobs = [ 166 idx 167 for idx, (progress, total) in enumerate(jobs) 168 if progress < total 169 ] 170 if not incomplete_jobs: 171 break 172 which = random.choice(incomplete_jobs) 173 jobs[which][0] += 1 174 progress = sum([progress for progress, total in jobs]) 175 176 bar.update(progress, jobs=jobs, force=True) 177 time.sleep(0.02) 178 179 180@example 181def granular_progress_example(): 182 widgets = [ 183 progressbar.GranularBar(markers=" ▏▎▍▌▋▊▉█", left='', right='|'), 184 progressbar.GranularBar(markers=" ▁▂▃▄▅▆▇█", left='', right='|'), 185 progressbar.GranularBar(markers=" ▖▌▛█", left='', right='|'), 186 progressbar.GranularBar(markers=" ░▒▓█", left='', right='|'), 187 progressbar.GranularBar(markers=" ⡀⡄⡆⡇⣇⣧⣷⣿", left='', right='|'), 188 progressbar.GranularBar(markers=" .oO", left='', right=''), 189 ] 190 for i in progressbar.progressbar(range(100), widgets=widgets): 191 time.sleep(0.03) 192 193 194@example 195def percentage_label_bar_example(): 196 widgets = [progressbar.PercentageLabelBar()] 197 bar = progressbar.ProgressBar(widgets=widgets, max_value=10).start() 198 for i in range(10): 199 # do something 200 time.sleep(0.1) 201 bar.update(i + 1) 202 bar.finish() 203 204 205@example 206def file_transfer_example(): 207 widgets = [ 208 'Test: ', progressbar.Percentage(), 209 ' ', progressbar.Bar(marker=progressbar.RotatingMarker()), 210 ' ', progressbar.ETA(), 211 ' ', progressbar.FileTransferSpeed(), 212 ] 213 bar = progressbar.ProgressBar(widgets=widgets, max_value=1000).start() 214 for i in range(100): 215 # do something 216 bar.update(10 * i + 1) 217 bar.finish() 218 219 220@example 221def custom_file_transfer_example(): 222 class CrazyFileTransferSpeed(progressbar.FileTransferSpeed): 223 ''' 224 It's bigger between 45 and 80 percent 225 ''' 226 def update(self, bar): 227 if 45 < bar.percentage() < 80: 228 return 'Bigger Now ' + progressbar.FileTransferSpeed.update( 229 self, bar) 230 else: 231 return progressbar.FileTransferSpeed.update(self, bar) 232 233 widgets = [ 234 CrazyFileTransferSpeed(), 235 ' <<<', progressbar.Bar(), '>>> ', 236 progressbar.Percentage(), 237 ' ', 238 progressbar.ETA(), 239 ] 240 bar = progressbar.ProgressBar(widgets=widgets, max_value=1000) 241 # maybe do something 242 bar.start() 243 for i in range(200): 244 # do something 245 bar.update(5 * i + 1) 246 bar.finish() 247 248 249@example 250def double_bar_example(): 251 widgets = [ 252 progressbar.Bar('>'), ' ', 253 progressbar.ETA(), ' ', 254 progressbar.ReverseBar('<'), 255 ] 256 bar = progressbar.ProgressBar(widgets=widgets, max_value=1000).start() 257 for i in range(100): 258 # do something 259 bar.update(10 * i + 1) 260 time.sleep(0.01) 261 bar.finish() 262 263 264@example 265def basic_file_transfer(): 266 widgets = [ 267 'Test: ', progressbar.Percentage(), 268 ' ', progressbar.Bar(marker='0', left='[', right=']'), 269 ' ', progressbar.ETA(), 270 ' ', progressbar.FileTransferSpeed(), 271 ] 272 bar = progressbar.ProgressBar(widgets=widgets, max_value=500) 273 bar.start() 274 # Go beyond the max_value 275 for i in range(100, 501, 50): 276 time.sleep(0.1) 277 bar.update(i) 278 bar.finish() 279 280 281@example 282def simple_progress(): 283 bar = progressbar.ProgressBar( 284 widgets=[progressbar.SimpleProgress()], 285 max_value=17, 286 ).start() 287 for i in range(17): 288 time.sleep(0.1) 289 bar.update(i + 1) 290 bar.finish() 291 292 293@example 294def basic_progress(): 295 bar = progressbar.ProgressBar().start() 296 for i in range(10): 297 time.sleep(0.1) 298 bar.update(i + 1) 299 bar.finish() 300 301 302@example 303def progress_with_automatic_max(): 304 # Progressbar can guess max_value automatically. 305 bar = progressbar.ProgressBar() 306 for i in bar(range(8)): 307 time.sleep(0.1) 308 309 310@example 311def progress_with_unavailable_max(): 312 # Progressbar can't guess max_value. 313 bar = progressbar.ProgressBar(max_value=8) 314 for i in bar((i for i in range(8))): 315 time.sleep(0.1) 316 317 318@example 319def animated_marker(): 320 bar = progressbar.ProgressBar( 321 widgets=['Working: ', progressbar.AnimatedMarker()]) 322 for i in bar((i for i in range(5))): 323 time.sleep(0.1) 324 325 326@example 327def filling_bar_animated_marker(): 328 bar = progressbar.ProgressBar(widgets=[ 329 progressbar.Bar( 330 marker=progressbar.AnimatedMarker(fill='#'), 331 ), 332 ]) 333 for i in bar(range(15)): 334 time.sleep(0.1) 335 336 337@example 338def counter_and_timer(): 339 widgets = ['Processed: ', progressbar.Counter('Counter: %(value)05d'), 340 ' lines (', progressbar.Timer(), ')'] 341 bar = progressbar.ProgressBar(widgets=widgets) 342 for i in bar((i for i in range(15))): 343 time.sleep(0.1) 344 345 346@example 347def format_label(): 348 widgets = [progressbar.FormatLabel( 349 'Processed: %(value)d lines (in: %(elapsed)s)')] 350 bar = progressbar.ProgressBar(widgets=widgets) 351 for i in bar((i for i in range(15))): 352 time.sleep(0.1) 353 354 355@example 356def animated_balloons(): 357 widgets = ['Balloon: ', progressbar.AnimatedMarker(markers='.oO@* ')] 358 bar = progressbar.ProgressBar(widgets=widgets) 359 for i in bar((i for i in range(24))): 360 time.sleep(0.1) 361 362 363@example 364def animated_arrows(): 365 # You may need python 3.x to see this correctly 366 try: 367 widgets = ['Arrows: ', progressbar.AnimatedMarker(markers='←↖↑↗→↘↓↙')] 368 bar = progressbar.ProgressBar(widgets=widgets) 369 for i in bar((i for i in range(24))): 370 time.sleep(0.1) 371 except UnicodeError: 372 sys.stdout.write('Unicode error: skipping example') 373 374 375@example 376def animated_filled_arrows(): 377 # You may need python 3.x to see this correctly 378 try: 379 widgets = ['Arrows: ', progressbar.AnimatedMarker(markers='◢◣◤◥')] 380 bar = progressbar.ProgressBar(widgets=widgets) 381 for i in bar((i for i in range(24))): 382 time.sleep(0.1) 383 except UnicodeError: 384 sys.stdout.write('Unicode error: skipping example') 385 386 387@example 388def animated_wheels(): 389 # You may need python 3.x to see this correctly 390 try: 391 widgets = ['Wheels: ', progressbar.AnimatedMarker(markers='◐◓◑◒')] 392 bar = progressbar.ProgressBar(widgets=widgets) 393 for i in bar((i for i in range(24))): 394 time.sleep(0.1) 395 except UnicodeError: 396 sys.stdout.write('Unicode error: skipping example') 397 398 399@example 400def format_label_bouncer(): 401 widgets = [ 402 progressbar.FormatLabel('Bouncer: value %(value)d - '), 403 progressbar.BouncingBar(), 404 ] 405 bar = progressbar.ProgressBar(widgets=widgets) 406 for i in bar((i for i in range(100))): 407 time.sleep(0.01) 408 409 410@example 411def format_label_rotating_bouncer(): 412 widgets = [progressbar.FormatLabel('Animated Bouncer: value %(value)d - '), 413 progressbar.BouncingBar(marker=progressbar.RotatingMarker())] 414 415 bar = progressbar.ProgressBar(widgets=widgets) 416 for i in bar((i for i in range(18))): 417 time.sleep(0.1) 418 419 420@example 421def with_right_justify(): 422 with progressbar.ProgressBar(max_value=10, term_width=20, 423 left_justify=False) as progress: 424 assert progress.term_width is not None 425 for i in range(10): 426 progress.update(i) 427 428 429@example 430def exceeding_maximum(): 431 with progressbar.ProgressBar(max_value=1) as progress: 432 try: 433 progress.update(2) 434 except ValueError: 435 pass 436 437 438@example 439def reaching_maximum(): 440 progress = progressbar.ProgressBar(max_value=1) 441 try: 442 progress.update(1) 443 except RuntimeError: 444 pass 445 446 447@example 448def stdout_redirection(): 449 with progressbar.ProgressBar(redirect_stdout=True) as progress: 450 print('', file=sys.stdout) 451 progress.update(0) 452 453 454@example 455def stderr_redirection(): 456 with progressbar.ProgressBar(redirect_stderr=True) as progress: 457 print('', file=sys.stderr) 458 progress.update(0) 459 460 461@example 462def negative_maximum(): 463 try: 464 with progressbar.ProgressBar(max_value=-1) as progress: 465 progress.start() 466 except ValueError: 467 pass 468 469 470@example 471def rotating_bouncing_marker(): 472 widgets = [progressbar.BouncingBar(marker=progressbar.RotatingMarker())] 473 with progressbar.ProgressBar(widgets=widgets, max_value=20, 474 term_width=10) as progress: 475 for i in range(20): 476 time.sleep(0.1) 477 progress.update(i) 478 479 widgets = [progressbar.BouncingBar(marker=progressbar.RotatingMarker(), 480 fill_left=False)] 481 with progressbar.ProgressBar(widgets=widgets, max_value=20, 482 term_width=10) as progress: 483 for i in range(20): 484 time.sleep(0.1) 485 progress.update(i) 486 487 488@example 489def incrementing_bar(): 490 bar = progressbar.ProgressBar(widgets=[ 491 progressbar.Percentage(), 492 progressbar.Bar(), 493 ], max_value=10).start() 494 for i in range(10): 495 # do something 496 time.sleep(0.1) 497 bar += 1 498 bar.finish() 499 500 501@example 502def increment_bar_with_output_redirection(): 503 widgets = [ 504 'Test: ', progressbar.Percentage(), 505 ' ', progressbar.Bar(marker=progressbar.RotatingMarker()), 506 ' ', progressbar.ETA(), 507 ' ', progressbar.FileTransferSpeed(), 508 ] 509 bar = progressbar.ProgressBar(widgets=widgets, max_value=100, 510 redirect_stdout=True).start() 511 for i in range(10): 512 # do something 513 time.sleep(0.01) 514 bar += 10 515 print('Got', i) 516 bar.finish() 517 518 519@example 520def eta_types_demonstration(): 521 widgets = [ 522 progressbar.Percentage(), 523 ' ETA: ', progressbar.ETA(), 524 ' Adaptive ETA: ', progressbar.AdaptiveETA(), 525 ' Absolute ETA: ', progressbar.AbsoluteETA(), 526 ' Transfer Speed: ', progressbar.FileTransferSpeed(), 527 ' Adaptive Transfer Speed: ', progressbar.AdaptiveTransferSpeed(), 528 ' ', progressbar.Bar(), 529 ] 530 bar = progressbar.ProgressBar(widgets=widgets, max_value=500) 531 bar.start() 532 for i in range(500): 533 if i < 100: 534 time.sleep(0.02) 535 elif i > 400: 536 time.sleep(0.1) 537 else: 538 time.sleep(0.01) 539 bar.update(i + 1) 540 bar.finish() 541 542 543@example 544def adaptive_eta_without_value_change(): 545 # Testing progressbar.AdaptiveETA when the value doesn't actually change 546 bar = progressbar.ProgressBar(widgets=[ 547 progressbar.AdaptiveETA(), 548 progressbar.AdaptiveTransferSpeed(), 549 ], max_value=2, poll_interval=0.0001) 550 bar.start() 551 for i in range(100): 552 bar.update(1) 553 time.sleep(0.1) 554 bar.finish() 555 556 557@example 558def iterator_with_max_value(): 559 # Testing using progressbar as an iterator with a max value 560 bar = progressbar.ProgressBar() 561 562 for n in bar(iter(range(100)), 100): 563 # iter range is a way to get an iterator in both python 2 and 3 564 pass 565 566 567@example 568def eta(): 569 widgets = [ 570 'Test: ', progressbar.Percentage(), 571 ' | ETA: ', progressbar.ETA(), 572 ' | AbsoluteETA: ', progressbar.AbsoluteETA(), 573 ' | AdaptiveETA: ', progressbar.AdaptiveETA(), 574 ] 575 bar = progressbar.ProgressBar(widgets=widgets, max_value=50).start() 576 for i in range(50): 577 time.sleep(0.1) 578 bar.update(i + 1) 579 bar.finish() 580 581 582@example 583def variables(): 584 # Use progressbar.Variable to keep track of some parameter(s) during 585 # your calculations 586 widgets = [ 587 progressbar.Percentage(), 588 progressbar.Bar(), 589 progressbar.Variable('loss'), 590 ', ', 591 progressbar.Variable('username', width=12, precision=12), 592 ] 593 with progressbar.ProgressBar(max_value=100, widgets=widgets) as bar: 594 min_so_far = 1 595 for i in range(100): 596 time.sleep(0.01) 597 val = random.random() 598 if val < min_so_far: 599 min_so_far = val 600 bar.update(i, loss=min_so_far, username='Some user') 601 602 603@example 604def user_variables(): 605 tasks = { 606 'Download': [ 607 'SDK', 608 'IDE', 609 'Dependencies', 610 ], 611 'Build': [ 612 'Compile', 613 'Link', 614 ], 615 'Test': [ 616 'Unit tests', 617 'Integration tests', 618 'Regression tests', 619 ], 620 'Deploy': [ 621 'Send to server', 622 'Restart server', 623 ], 624 } 625 num_subtasks = sum(len(x) for x in tasks.values()) 626 627 with progressbar.ProgressBar( 628 prefix='{variables.task} >> {variables.subtask}', 629 variables={'task': '--', 'subtask': '--'}, 630 max_value=10 * num_subtasks) as bar: 631 for tasks_name, subtasks in tasks.items(): 632 for subtask_name in subtasks: 633 for i in range(10): 634 bar.update(bar.value + 1, task=tasks_name, 635 subtask=subtask_name) 636 time.sleep(0.1) 637 638 639@example 640def format_custom_text(): 641 format_custom_text = progressbar.FormatCustomText( 642 'Spam: %(spam).1f kg, eggs: %(eggs)d', 643 dict( 644 spam=0.25, 645 eggs=3, 646 ), 647 ) 648 649 bar = progressbar.ProgressBar(widgets=[ 650 format_custom_text, 651 ' :: ', 652 progressbar.Percentage(), 653 ]) 654 for i in bar(range(25)): 655 format_custom_text.update_mapping(eggs=i * 2) 656 time.sleep(0.1) 657 658 659@example 660def simple_api_example(): 661 bar = progressbar.ProgressBar(widget_kwargs=dict(fill='█')) 662 for i in bar(range(200)): 663 time.sleep(0.02) 664 665 666@example 667def ETA_on_generators(): 668 def gen(): 669 for x in range(200): 670 yield None 671 672 widgets = [progressbar.AdaptiveETA(), ' ', 673 progressbar.ETA(), ' ', 674 progressbar.Timer()] 675 676 bar = progressbar.ProgressBar(widgets=widgets) 677 for i in bar(gen()): 678 time.sleep(0.02) 679 680 681@example 682def percentage_on_generators(): 683 def gen(): 684 for x in range(200): 685 yield None 686 687 widgets = [progressbar.Counter(), ' ', 688 progressbar.Percentage(), ' ', 689 progressbar.SimpleProgress(), ' '] 690 691 bar = progressbar.ProgressBar(widgets=widgets) 692 for i in bar(gen()): 693 time.sleep(0.02) 694 695 696def test(*tests): 697 if tests: 698 for example in examples: 699 700 for test in tests: 701 if test in example.__name__: 702 example() 703 break 704 705 else: 706 print('Skipping', example.__name__) 707 else: 708 for example in examples: 709 example() 710 711 712if __name__ == '__main__': 713 try: 714 test(*sys.argv[1:]) 715 except KeyboardInterrupt: 716 sys.stdout('\nQuitting examples.\n') 717