python2.7 print函数中\r的作用

发布于 2022-09-06 13:20:52 字数 1585 浏览 12 评论 0

这是搜索到的一段progress bar的代码:

from __future__ import print_function
# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '|'):
    """
    Call in a loop to create terminal progress bar
    @params:
        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - Optional  : positive number of decimals in percent complete (Int)
        length      - Optional  : character length of bar (Int)
        fill        - Optional  : bar fill character (Str)
    """
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = '\r')
    # Print New Line on Complete
    if iteration == total:
        print()
from time import sleep

# A List of Items
items = list(range(0, 57))
l = len(items)

# Initial call to print 0% progress
printProgressBar(0, l, prefix = 'Progress:', suffix = 'Complete', length = 50)

print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = '\r')

这里的 第一个 \r 起到了什么作用呢? 我知道这个是让光标回到行首 这个end='r'不是已经在每一行都做这个操作了吗?

另外:如果去掉第一个r 也能显示进度条 但是很不流畅,好像缓冲区没有在每一次print的时候清空,难道r还有清空缓冲区的作用?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情深缘浅 2022-09-13 13:20:52

亲测没有任何作用。
想流畅,输出后应该用 sys.stdout.flush 清空缓冲区。

我恋#小黄人 2022-09-13 13:20:52

\r可以把缓冲区最后一行清掉。

你可以试试下面的代码,它展示了个小动画。

import sys
import time

symbols = ['\r|', '\r/', '\r-', '\r\\']

i = 0
while True:
    sys.stdout.write(symbols[i])
    sys.stdout.flush()
    time.sleep(0.5)
    i = (i + 1) % 4
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文