最新消息:

Python中如何写控制台进度条的整理

Python admin 1676浏览 0评论

进度条和一般的print区别在哪里呢?

答案就是print会输出一个\n,也就是换行符,这样光标移动到了下一行行首,接着输出,之前已经通过stdout输出的东西依旧保留,而且保证我们在下面看到最新的输出结果。

进度条不然,我们必须再原地输出才能保证他是一个进度条,否则换行了怎么还叫进度条?

最简单的办法就是,再输出完毕后,把光标移动到行首,继续在那里输出更长的进度条即可实现,新的更长的进度条把旧的短覆盖,就形成了动画效果。

可以想到那个转义符了吧,那就是 \r。

转义符\r就可以把光标移动到行首而不换行,转义符\n就把光标移动到行首并且换行。

在python中,输出stdout(标准输出)可以使用sys.stdout.write
例如:

#!/usr/bin/env python
# -*- coding=utf-8 -*-
#Using GPL v2
#Author: ihipop@gmail.com
##2010-10-27 22:07
"""
Usage:
Just A Template
"""
from __future__ import division
 
import sys,time
j = '#'
if __name__ == '__main__':
    for i in range(1,61):
        j += '#'
        sys.stdout.write(str(int((i/60)*100))+'%  ||'+j+'->'+"\r")
        sys.stdout.flush()
        time.sleep(0.5)
print

第二种思路是用转义符\b
转义符\b是退格键,也就是说把输出的光标往回退格子,这样就可以不用+=了,例如:

#!/usr/bin/env python
# -*- coding=utf-8 -*-
#Using GPL v2
#Author: ihipop@gmail.com
#2010-10-27 22:07
"""
Usage:
Just A Template
"""
from __future__ import division
 
import sys,time
if __name__ == '__main__':
    for i in range(1,61):
        sys.stdout.write('#'+'->'+"\b\b")
        sys.stdout.flush()
        time.sleep(0.5)
print

光标回退2格,写个#再回退,再写,达到增长的目的了


不过写这么多似乎是废话,在耳边常常听到一句话:那就是不要重复造轮子。实际上python有丰富发lib帮你实现这个东西,你完全可以把心思放在逻辑开发上而不用注意这些小细节

下面要介绍的就是这个类“progressbar”(http://code.google.com/p/python-progressbar/),使用easy_install可以方便的安装这可个类库,其实就一个文件,拿过来放到文件同一个目录下面也直接可以import过来

下面就是基本使用举例:

# -*- coding=utf-8 -*-
#Using GPL v2
#Author: ihipop@gmail.com
#2010-10-27 22:53
"""
Usage:
Just A Template
"""
from __future__ import division
 
import sys,time
from progressbar import *
total = 1000
 
#基本用法
progress = ProgressBar()
for i in progress(range(total)):
  time.sleep(0.01)
 
pbar = ProgressBar().start()
for i in range(1,1000):
    pbar.update(int((i/(total-1))*100))
    time.sleep(0.01)
pbar.finish()
 
#高级用法
widgets = ['Progress: ', Percentage(), ' ', Bar(marker=RotatingMarker('>-=')),
           ' ', ETA(), ' ', FileTransferSpeed()]
pbar = ProgressBar(widgets=widgets, maxval=10000000).start()
for i in range(1000000):
  # do something
  pbar.update(10*i+1)
  time.sleep(0.0001)
pbar.finish()

官方示例下载,移步这里:http://code.google.com/p/python-progressbar/source/browse/progressbar/examples.py


再发一个类:

# -*- coding=utf-8 -*-
#Using GPL v2
#Author: ihipop@gmail.com
#2010-10-30 13:59
"""
Usage:
Just A Template
"""
class progressbarClass:
    def __init__(self, finalcount, progresschar=None):
        import sys
        self.finalcount=finalcount
        self.blockcount=0
        #
        # See if caller passed me a character to use on the
        # progress bar (like "*").  If not use the block
        # character that makes it look like a real progress
        # bar.
        #
        if not progresschar: self.block=chr(178)
        else:                self.block=progresschar
        #
        # Get pointer to sys.stdout so I can use the write/flush
        # methods to display the progress bar.
        #
        self.f=sys.stdout
        #
        # If the final count is zero, don't start the progress gauge
        #
        if not self.finalcount : return
        self.f.write('\n------------------- % Progress -------------------\n')
        return
 
    def progress(self, count):
        #
        # Make sure I don't try to go off the end (e.g. >100%)
        #
        count=min(count, self.finalcount)
        #
        # If finalcount is zero, I'm done
        #
        if self.finalcount:
            percentcomplete=int(round(100*count/self.finalcount))
            if percentcomplete < 1: percentcomplete=1
        else:
            percentcomplete=100
            
        #print "percentcomplete=",percentcomplete
        blockcount=int(percentcomplete/2)
        #print "blockcount=",blockcount
        if blockcount > self.blockcount:
            for i in range(self.blockcount,blockcount):
                self.f.write(self.block)
                self.f.flush()
                
        if percentcomplete == 100: self.f.write("\n")
        self.blockcount=blockcount
        return
    
if __name__ == "__main__":
    from time import sleep
    pb=progressbarClass(8,"*")
    count=0
    while count<9:
        count+=1
        pb.progress(count)
        sleep(0.2)

 

转自:http://blog.ihipop.info/2010/10/1736.html

 

—————————————————————————————————–

ps:最简单的进度条显示或者覆盖显示,就是第一种那样,不使用print,而是使用sys.stdout.write()和sys.stdout.flush()配合\r来实现。不过在实际使用中遇到的问题是,如果被覆盖的字符长于覆盖的字符会导致不能完全覆盖,可以使用字符串.ljust()等函数来格式化要输出的字符使之等长。

如在写扫描wp插件代码时,由于每个插件的名字长度不同,如果想要实时刷新显示正在扫描的插件名字就必须要将插件的名字格式化输出,即

		try:
			r = self.http.request('GET',page)
			if (r.status ==200) or (r.status==403):
				s = 'find plugin %s' % plugin_name.ljust(40)
				sys.stdout.write('\r%s\n' % s)
				sys.stdout.flush()
			else:
				s = "not find plugin %s" % plugin_name[:36].ljust(36)
				sys.stdout.write('\r%s' % s)
				sys.stdout.flush()
		except Exception,e:
			print e
			time.sleep(5)

 

转载请注明:jinglingshu的博客 » Python中如何写控制台进度条的整理

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址