Created
August 8, 2012 14:59
-
-
Save scturtle/3295668 to your computer and use it in GitHub Desktop.
console progress in python
This file contains 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
#!/usr/bin/env python | |
import os | |
import sys | |
class Progress: | |
def __init__(self, fillchar='#', width=80): | |
self.fillchar = fillchar | |
self.width = width | |
def update(self, percent, info=''): | |
length = self.width | |
percent_str = str(int(round(percent))) + '% ' | |
length -= len(percent_str) | |
if info: | |
info = ' ' + info | |
length -= len(info) | |
if length <= 2: | |
raise Exception('info is too long!') | |
length -= 2 | |
fill_length = int(percent / 100.0 * length) | |
progress = '[{0:{1}}]'.format(self.fillchar * fill_length, length) | |
if sys.platform.startswith('win'): | |
os.system('cls') | |
sys.stdout.write('{}{}{}'.format(percent_str, progress, info)) | |
sys.stdout.write('\n' if percent == 100.0 else '\r') | |
sys.stdout.flush() | |
if __name__ == '__main__': | |
import time | |
p = Progress() | |
for i in range(0, 100 + 1, 10): | |
p.update(float(i), 'Hello progress!') | |
time.sleep(0.2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment