Python 命令行加载栏

Python command line loading bar

我看到终端中显示了几个不同的加载栏。但是,其中一些依赖 \r 似乎不起作用,这可能是因为我使用 Python 2.7 而不是 3.X.

我有一个加载栏,但它每次都打印一个新行。

def update_progress(progress):
    print"\r [{0}] {1}%".format('#'*(progress/10), progress)

while prog != 101:
    update_progress(prog)
    prog = prog + 1`

我是 Python 的新手,所以如果您能使代码简短易懂的话。这个 post 可能看起来像一个重复的问题,但 Stack Overflow 上的其他一些问题不起作用或换行打印。

如果 \r 应该可以在 Python 2.7 上运行,那么您能否解释一下如何修复它,因为它不起作用?然而,这让我感到困惑,因为 \n 工作得很好,但这是另一个问题。

P.S: 我也需要它在再次打印之前清除行。

谢谢 永远清醒

除了你从不初始化 prog 的事实(我想你想要
prog = 0while 循环之前)你可以抑制换行符的打印 - Python2 中的字符,方法是在语句后添加逗号:

def update_progress(progress):
    print "\r [{0}] {1}%".format('#'*(progress//10), progress),

不过,在阅读代码时,那个逗号很难漏掉,所以导入并使用Python 3 print函数会更好。

from __future__ import print_function

def update_progress(progress):
    print("\r [{0}] {1}%".format('#'*(progress//10), progress), end='')

您需要使用 sys.stdout.write() 因为 print() 添加了一个新行:

import sys
def update_progress(progress):
    sys.stdout.write("\r [{0}] {1}%".format('#'*(progress/10), progress))

while prog != 101:
    update_progress(prog)
    prog = prog + 1

另请注意,在 python3 中,您可以将参数 endprint() 一起使用:

 print("\r [{0}] {1}%".format('#'*(progress/10), progress), end='')

请使用sys.stdout.write("yourstring"),然后使用sys.stdout.flush()确保显示内容。为了在跨平台开发中做图形化的事情,我建议你使用 Python 库 termcolorcolorama。他们将为 windows 命令行着色,以便您可以制作 漂亮的 进度条。如果你想发布你的项目,你可以将 coloramatermcolor 的代码实现到你的代码中,并且你有一个文件。

玩得开心 Python

名人堂