Python缓存区刷新到终端

2018-10-04  本文已影响0人  MononokeHime

程序是如何将数据输出到终端的呢?你肯定会说调用了print方法,那print方法内部是怎么实现的呢?事实上,print的内部实现了标准的输出流,先将数据输出到缓冲区,再将缓冲区里的数据刷新到终端显示。

数据从缓冲区刷新到终端:

示例一:旋转符号

import sys,time
s = ["\\","|","/","-","|","-"]
while True:
    for i in s: 
        sys.stdout.write("\r")  # 清空终端并清空缓冲区
        sys.stdout.write(i) # 往缓冲区里写数据
        sys.stdout.flush() # 将缓冲区里的数据刷新到终端,但是不会清空缓冲区
        time.sleep(0.5)
10月-05-2018 10-13-43.gif

示例二:下载进度条

import time
import sys

class SimpleProgressBar():
    def __init__(self, width=50):
        self.last_x = -1
        self.width = width

    def update(self, x):
        assert 0 <= x <= 100 # `x`: progress in percent ( between 0 and 100)
        if self.last_x == int(x): return
        self.last_x = int(x)
        pointer = int(self.width * (x / 100.0))
        sys.stdout.write( '\r%d%% [%s]' % (int(x), '#' * pointer + '.' * (self.width - pointer)))
        sys.stdout.flush()
        if x == 100: print('')

pb = SimpleProgressBar()
for i in range(301):
    pb.update(i*100.0/300)
    time.sleep(0.1)
10月-05-2018 10-08-01.gif
上一篇 下一篇

猜你喜欢

热点阅读