【问题标题】:Reset the cursor to newline AFTER setting it to the beginning using `end="\r"`在使用 `end="\r"` 将光标设置为开头之后,将光标重置为换行符
【发布时间】:2021-11-17 22:00:17
【问题描述】:

print() 函数有一个非常有用的参数end,它允许您自定义打印结束时的文本以及打印后光标的位置。例如,您可以多次使用end='\r'print the text on same line,这对于创建进度条和完成百分比语句非常有用。

但是如何在将光标设置为开头后将其重置回换行符?例如以下代码:

import datetime

start_time = datetime.datetime.now()
sampleRange = range(10)
for i in range(10):
    i=i+1
    percentComplete = str(i/len(sampleRange)*100)
    print(percentComplete + "% done", end="\r")
    if i==5:
        timeTaken = str(datetime.datetime.now() - start_time)
        print(str(i) + "loops done in " + timeTaken)

产生一个输出:

5loops done in 0:00:00.001001
100.0% done

但预期的输出是:

50% done
5loops done in 0:00:00.001001
100.0% done

这有助于在必要时向进度条添加里程碑。

【问题讨论】:

    标签: python


    【解决方案1】:

    这里的诀窍是在第二个 print(...) 语句之前的 if 条件中简单地添加一个 print() 语句,不带任何参数将光标重置为默认行为

    #...
        if i==5:
            print() # this sends the cursor to the next line without changing anything in the current line
            print(str(i) + "loops done in " + timeTaken)
    

    提示

    对于好奇的人,以下是有关如何使用 python 在终端中打印进度条的资源:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-20
      • 1970-01-01
      • 2014-04-27
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多