Last active
April 11, 2016 03:24
-
-
Save efraintorlo/99a93bb6c401bdf652ec86ab6b8f3bf7 to your computer and use it in GitHub Desktop.
Progress Bar. Print a simple progress bar in Terminal.
The bar length is dynamically resized if the terminal window size is changed.
Includes a simple example in main() function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def progressbar(advance, total, mark='=', bar_length=None): | |
| """ | |
| Print Progress Bar in terminal: | |
| ARGS: | |
| advance (int): Typically is a ``loop for index``. | |
| total (int): The total number of steps in the ``loop for`` | |
| mark (str): Is the mark used inside the progress bar. | |
| Default is '=' | |
| bar_lenght (float): Is the window-ratio to be filled by the | |
| progress bar. | |
| 0 < bar_length < 1 | |
| Default is 2/3 | |
| RETURN: | |
| Progress bar printed in terminal. | |
| [= ] 10% | |
| [=== ] 30% | |
| [==========] 100% DONE! | |
| """ | |
| import sys | |
| terminal_width = _get_terminal_width() | |
| if bar_length is None: | |
| bar_width = int((2/3)*terminal_width) | |
| else: | |
| bar_width = int(bar_length*terminal_width) | |
| sys.stdout.write('\r') | |
| sys.stdout.write("[{mark:{fill}{width}}] {adv}%".format(mark=mark*int(bar_width*(advance)/total), | |
| fill='', width=bar_width, adv=int(100*advance/total))) | |
| sys.stdout.flush() | |
| if advance == total: | |
| print ' DONE!\n' | |
| def _get_terminal_width(): | |
| """ | |
| Get the terminal width dinamically. | |
| ARGS: None | |
| RETURN: | |
| width (int): Returns the result ``tput cold`` | |
| """ | |
| import subprocess | |
| command = ['tput', 'cols'] | |
| try: | |
| width = int(subprocess.check_output(command)) | |
| except OSError as e: | |
| print("Invalid Command '{0}': exit status ({1})".format( | |
| command[0], e.errno)) | |
| except subprocess.CalledProcessError as e: | |
| print("Command '{0}' returned non-zero exit status: ({1})".format( | |
| command, e.returncode)) | |
| else: | |
| return width | |
| def main(): | |
| import time | |
| for i in xrange(10): | |
| time.sleep(1) | |
| progressbar(advance=i+1, total=10, mark="*") | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment