Windows Python IDEL编译器自动忽略'\r'及简单进度条的实现

来源:互联网 发布:nginx 子域名 重定向 编辑:程序博客网 时间:2024/06/05 08:44

Windows环境下,Python自带的IDEL编译器在进行字符串输出时会忽略字符串结尾的'\r'导致光标无法回到行首。

另在DOS窗口下采用Python print.py运行 运行的结果正确。

附简单进度条代码。

使用'\r'回到行首和sys.stdout.write/flush输出并刷新缓冲区。

注意特殊字符实心方块的编码方式。


# coding=utf-8import sys,timet = "▉"t = t.decode("utf-8")class ProgressBar:    def __init__(self, count = 0, total = 0, width = 20):        self.count = count        self.total = total        self.width = width    def move(self):        self.count += 1    def log(self, s):         progress = self.width * self.count / self.total        sys.stdout.write('{0:3}/{1:3}: \r'.format(self.count, self.total))        sys.stdout.flush()        sys.stdout.write(t* progress + '--' * (self.width - progress)+'\r')        print s        if progress == self.width:            sys.stdout.write('Done!')        else :            sys.stdout.write('Please waitting!\n\r')num = 10bar = ProgressBar(total=num)for i in range(num):    bar.move()    bar.log('%2d'%((float)(i+1)/num*100)+'%\r')    time.sleep(1)


0 0
原创粉丝点击