美文网首页
Python缓存区刷新到终端

Python缓存区刷新到终端

作者: MononokeHime | 来源:发表于2018-10-04 22:11 被阅读0次

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

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

  • flush():手动将缓冲区的数据刷新到终端,但是不会清空缓冲区
  • 当缓冲区满时,自动刷新到终端,并清空缓冲区
  • 程序终止时,缓冲区数据自动刷新到终端,并清空缓冲区
  • write("\n") :遇到\n时,将缓冲区里的数据刷新到终端,并清空缓冲区
  • write("\r") :遇到\r时,清空缓冲区数据并清空终端信息

示例一:旋转符号

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

相关文章

网友评论

      本文标题:Python缓存区刷新到终端

      本文链接:https://www.haomeiwen.com/subject/xvqfaftx.html