當使用工具,如bzr
,doxygen
和scp
或wget
,我看到他們都有一個不錯的進度條,看上去像這樣:創建一個CLI應用程序中的進度條
|=============>---------| 55% ETA 3:30
我試着寫東西就像我在C++中使用\b
這個字符的次數一樣多,就像我之前寫過的東西一樣。輸出閃爍得很厲害,看起來沒有上述工具那麼流暢。
我怎樣才能順利地用Python創建這樣一個進度條(或至少改變顯示的ETA)?
當使用工具,如bzr
,doxygen
和scp
或wget
,我看到他們都有一個不錯的進度條,看上去像這樣:創建一個CLI應用程序中的進度條
|=============>---------| 55% ETA 3:30
我試着寫東西就像我在C++中使用\b
這個字符的次數一樣多,就像我之前寫過的東西一樣。輸出閃爍得很厲害,看起來沒有上述工具那麼流暢。
我怎樣才能順利地用Python創建這樣一個進度條(或至少改變顯示的ETA)?
使用「\ r」將光標發送到行首。每秒重複打印不超過2-3次,以避免閃爍。
訣竅是使用\ r而不是(...)printf(「\ b」)。謝謝! –
,這可能是有用的例子:?如何在Python中的文件拷貝進度指示條]
http://code.google.com/p/corey-projects/source/browse/trunk/python2/progress_bar.py
import sys
import time
class ProgressBar:
def __init__(self, duration):
self.duration = duration
self.prog_bar = '[]'
self.fill_char = '#'
self.width = 40
self.__update_amount(0)
def animate(self):
for i in range(self.duration):
if sys.platform.lower().startswith('win'):
print self, '\r',
else:
print self, chr(27) + '[A'
self.update_time(i + 1)
time.sleep(1)
print self
def update_time(self, elapsed_secs):
self.__update_amount((elapsed_secs/float(self.duration)) * 100.0)
self.prog_bar += ' %ds/%ss' % (elapsed_secs, self.duration)
def __update_amount(self, new_amount):
percent_done = int(round((new_amount/100.0) * 100.0))
all_full = self.width - 2
num_hashes = int(round((percent_done/100.0) * all_full))
self.prog_bar = '[' + self.fill_char * num_hashes + ' ' * (all_full - num_hashes) + ']'
pct_place = (len(self.prog_bar)/2) - len(str(percent_done))
pct_string = '%d%%' % percent_done
self.prog_bar = self.prog_bar[0:pct_place] + \
(pct_string + self.prog_bar[pct_place + len(pct_string):])
def __str__(self):
return str(self.prog_bar)
if __name__ == '__main__':
""" example usage """
# print a static progress bar
# [########## 25% ] 15s/60s
p = ProgressBar(60)
p.update_time(15)
print 'static progress bar:'
print p
# print a static progress bar
# [=================83%============ ] 25s/30s
p = ProgressBar(30)
p.fill_char = '='
p.update_time(25)
print 'static progress bar:'
print p
# print a dynamic updating progress bar on one line:
#
# [################100%##################] 10s/10s
# done
secs = 10
p = ProgressBar(secs)
print 'dynamic updating progress bar:'
print 'please wait %d seconds...' % secs
# spawn asych (threads/processes/etc) code here that runs for secs.
# the call to .animate() blocks the main thread.
p.animate()
print 'done'
的
Python食譜有類似的東西。 – new123456
所以訣竅是在for循環中使用回車代替backspace char大約30次? –
可能重複(http://stackoverflow.com/questions/274493/how-to-copy-a-file-in-python-with-a-progress-bar) –
http://nadiana.com/animated-terminal-progress-bar-in-python – Xavier
其中一件好事開源代碼是您可以真正獲取代碼並查看代碼並瞭解它們是如何實現的。 ;-) – Keith