Simple implementation of python progress bar script
- 2020-06-15 09:45:50
- OfStack
Recently, I need to use Python to write a small script, which USES 1 little knowledge. Please find time to record 1. Not deep but often used.
Two progress bar examples, copy to run:
# coding=utf-8
import sys
import time
# width: Width, percent: The percentage
def progress(width, percent):
print "\r%s %d%%" % (('%%-%ds' % width) % (width * percent / 100 * '='), percent),
if percent >= 100:
print
sys.stdout.flush()
# The sample 1. 0%--100%
def demo1():
for i in xrange(100):
progress(50, (i + 1))
time.sleep(0.1)
## The sample 2. Cycle loading
def demo2():
i = 19
n = 200
while n > 0:
print "\t\t\t%s \r" % (i * "="),
i = (i + 1) % 20
time.sleep(0.1)
n -= 1
demo1()
demo2()
Provides a simple, self-written asynchronous progress bar that can be turned on before time-consuming operations and then stopped at the end of time-consuming operations.
import time
import thread
import sys
class Progress:
def __init__(self):
self._flag = False
def timer(self):
i = 19
while self._flag:
print "\t\t\t%s \r" % (i * "="),
sys.stdout.flush()
i = (i + 1) % 20
time.sleep(0.05)
print "\t\t\t%s\n" % (19 * "="),
thread.exit_thread()
def start(self):
self._flag = True
thread.start_new_thread(self.timer, ())
def stop(self):
self._flag = False
time.sleep(1)
Usage:
progress = Progress()
progress.start()
time.sleep(5)
progress.stop()