Python2.7用sys.stdout.write实现打印刷新(多个print显示在一行)

如何能在控制台实现在一行中显示进度的信息呢,就像使用pip安装时的进度那样。

如果用print则会打印成多行,下面这个小技巧可以在一行中打印: 

import time
import sys

if __name__ == "__main__":
    for i in range(1,101):
        sys.stdout.write('
{}>{}%'.format('='*(i/10), i))
        time.sleep(0.1)
        sys.stdout.flush()

其关键就在于使用' '这个转义字符(回到行首),sys.stdout.write首先打印这一行后不带任何结尾,使用了转义字符" "使得光标回到行首,再把缓冲区显示出来,就得到了我们所需要的效果。

效果如下动图:

另外这里有一个别人写的进度的第三方库:https://pypi.python.org/pypi/progressbar2

---------------------------------------------------------------------------------

关注微信公众号即可在手机上查阅,并可接收更多测试分享~

原文地址:https://www.cnblogs.com/songzhenhua/p/11704196.html