Skip to content

Instantly share code, notes, and snippets.

@j0hn
Created May 10, 2011 12:34
Show Gist options
  • Save j0hn/964387 to your computer and use it in GitHub Desktop.
Save j0hn/964387 to your computer and use it in GitHub Desktop.
Loading bar
#!/usr/bin/env python
# encoding: utf-8
import os
import sys
import fcntl
import struct
import termios
import threading
from time import sleep
def getTerminalSize():
"""
Returns (width, height) of your current terminal.
"""
def ioctl_GWINSZ(fd):
try:
cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
'1234'))
except:
return None
return cr
cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
if not cr:
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
cr = ioctl_GWINSZ(fd)
os.close(fd)
except:
pass
if not cr:
try:
cr = (env['LINES'], env['COLUMNS'])
except:
cr = (25, 80)
return int(cr[1]), int(cr[0])
class ProgressBar(threading.Thread):
"""
Displays a progress bar.
"""
def __init__(self, total_items, message="Loading...", width=None):
threading.Thread.__init__(self)
self.total = total_items
self.processed = 0
self.message = message
self.spin = u"|/—\\"
self.spin_index = 0
self.delay = 0.08
if not width:
self.fixed_width = False
else:
self.fixed_width = True
self.width = width
def progress(self):
"""
Progress one step.
"""
self.processed += 1
def run(self):
"""
Main loop.
"""
stop = False
while not stop:
self.spin_index = (self.spin_index + 1) % len(self.spin)
if not self.fixed_width:
self.width = getTerminalSize()[0] - 35
perc = 100.0 * self.processed / self.total
completed = self.width * self.processed / self.total
bar = "#" * completed + " " * (self.width - completed)
result_data = (self.message, bar, perc, self.processed,
self.total, self.spin[self.spin_index])
sys.stdout.write("\r%s [%s] %.2f%% (%d/%d) %s" % result_data)
if self.processed == self.total:
stop = True
print
sys.stdout.flush()
sleep(self.delay)
if __name__ == "__main__":
from random import random
total = 35
p = ProgressBar(total)
p.start()
for i in range(total):
p.progress()
sleep(random() / 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment