【问题标题】:Python - Updating Multiple Lines [duplicate]Python - 更新多行[重复]
【发布时间】:2020-04-10 00:26:05
【问题描述】:

我尝试在更新时打印多行,例如:

Attempts1: 10
Attempts2: 10

我试过了:

from time import sleep
import subprocess

while True:
  for number in range(100):
    print("Attempts1: {}".format(number))
    print("Attempts2: {}".format(number))
    sleep(0.1)
    subprocess.call("clear")

但文字一直在闪烁,这不是我想要的。

然后我尝试了这个:

from time import sleep

while True:
  for number in range(100):
    print("Attempts1: {}".format(number), end='\r', flush=True)
    print("Attempts2: {}".format(number), end='\r', flush=True)
    sleep(0.1)

得到这个:

Attempts1:1
Attempts2:1
Attempts1:2
Attempts2:2

等等

【问题讨论】:

  • 文本一直在闪烁,因为您每秒清屏 10 次。如果您不希望它闪烁,请使用光标控制字符覆盖文本,而不是重写整个屏幕。请参阅引用的副本作为起点。
  • 我已经使用了引用的副本并且它可以工作,但我试图用多行来做,而不仅仅是一个。
  • 您必须扩展副本显示的内容并使用垂直光标移动字符。

标签: python


【解决方案1】:

如果您更改订单,您的第一次尝试会成功

import os
while True:
    for number in range(100):
        os.system("clear")

        print("Attempts1: {}".format(number))
        print("Attempts2: {}".format(number))
        sleep(0.1)

希望对你有帮助。

【讨论】:

  • 它确实有效,但由于它每 100 毫秒更新一次,因此屏幕闪烁速度非常快。
猜你喜欢
  • 2012-10-01
  • 1970-01-01
  • 2019-05-26
  • 1970-01-01
  • 2022-12-16
  • 1970-01-01
  • 2016-08-31
  • 2011-10-30
  • 2013-09-22
相关资源
最近更新 更多