【问题标题】:How to clear only last one line in python output console?如何在 python 输出控制台中只清除最后一行?
【发布时间】:2017-06-15 10:55:21
【问题描述】:

我试图从输出控制台窗口中只清除最后几行。为了实现这一点,我决定使用创建秒表,我已经实现了在键盘中断和输入键按下时中断它会创建圈,但我的代码只创建圈一次,我当前的代码正在清除整个输出屏幕。

clear.py

import os
import msvcrt, time
from datetime import datetime
from threading import Thread

def threaded_function(arg):
    while True:
        input()

lap_count = 0
if __name__ == "__main__":
    # thread = Thread(target = threaded_function)
    # thread.start()
    try:
        while True:
            t = "{}:{}:{}:{}".format(datetime.now().hour, datetime.now().minute, datetime.now().second, datetime.now().microsecond)
            print(t)
            time.sleep(0.2)
            os.system('cls||clear') # I want some way to clear only previous line instead of clearing whole console
            if lap_count == 0:
                if msvcrt.kbhit():
                    if msvcrt.getwche() == '\r': # this creates lap only once when I press "Enter" key
                        lap_count += 1
                        print("lap : {}".format(t))
                        time.sleep(1)
                        continue            
    except KeyboardInterrupt:
        print("lap stop at : {}".format(t))
        print(lap_count)

当我跑步时

%run <path-to-script>/clear.py 

在我的 ipython shell 中,我只能创建一圈,但它不会永久保留。

【问题讨论】:

  • this 帖子的答案对 Python 2、Python 3、IPython notebook 和 jupyter notebook 的案例有很好的解释和选择。

标签: python python-3.x ipython python-3.4


【解决方案1】:

只清除输出中的一行:

print ("\033[A                             \033[A")

这将清除前一行并将光标置于行首。 如果你去掉尾随的换行符,那么它将转移到上一行,因为\033[A 意味着将光标向上移动一行

【讨论】:

  • print ("\033[A\033[A")
  • 当我使用它时,由于某种原因,这似乎会导致问题,它会清除行但也会向上移动打印。
【解决方案2】:

Ankush Rathi 在此评论上方分享的代码可能是正确的,除了在 print 命令中使用括号。我个人建议这样做。

print("This message will remain in the console.")

print("This is the message that will be deleted.", end="\r")

但要记住的一件事是,如果您在 IDLE 中按 F5 运行它,shell 仍将显示这两条消息。但是,如果您通过双击运行程序,输出控制台会将其删除。这可能是对 Ankush Rathi 的回答(在以前的帖子中)发生的误解。

【讨论】:

  • 如果消息很长并且跨越多行,则只删除最后一行,而不是整条消息。 (实际上,仅在 Ubuntu 中使用终端应用程序尝试过)。
【解决方案3】:

我认为最简单的方法是使用两个print()来实现清理最后一行。

print("something will be updated/erased during next loop", end="")
print("\r", end="")
print("the info")

第一个print() 只需确保光标在行尾结束,而不是开始新行

第二个print() 会将光标移动到同一行的开头,而不是开始新行

然后自然而然的第三个print() 就开始打印光标当前所在的位置。

我还做了一个玩具功能,使用循环和time.sleep()打印进度条,去看看

def progression_bar(total_time=10):
    num_bar = 50
    sleep_intvl = total_time/num_bar
    print("start: ")
    for i in range(1,num_bar):
        print("\r", end="")
        print("{:.1%} ".format(i/num_bar),"-"*i, end="")
        time.sleep(sleep_intvl)

【讨论】:

  • 这实际上是关于删除一行的最佳答案!
  • 你需要在函数末尾添加print("\r", end="") print("{:.1%} ".format(1), "-" * num_bar, end=""),否则会在98%处停止。否则这真的很有帮助,谢谢!
【解决方案4】:

我知道这是一个非常古老的问题,但我找不到任何好的答案。您必须使用转义字符。 Ashish Ghodake 建议使用这个

print ("\033[A                             \033[A")

但是,如果您要删除的行中的字符多于字符串中的空格怎么办? 我认为更好的办法是找出终端的一行可以容纳多少个字符,然后像这样在转义字符串中添加对应的“”号。

import subprocess, time
tput = subprocess.Popen(['tput','cols'], stdout=subprocess.PIPE)
cols = int(tput.communicate()[0].strip()) # the number of columns in a line
i = 0
while True:
    print(i)
    time.sleep(0.1)
    print("\033[A{}\033[A".format(' '*cols))
    i += 1

最后我想说删除最后一行的“功能”是

import subprocess
def remove():
    tput = subprocess.Popen(['tput','cols'], stdout=subprocess.PIPE)
    cols = int(tput.communicate()[0].strip())
    print("\033[A{}\033[A".format(' '*cols))

【讨论】:

  • 为什么使用''.join([' ']*cols) 而不仅仅是' '*cols
  • @Shreya 在我写答案的时候,我不太了解 Python,字符串乘法对我来说似乎很奇怪。但是没有什么特别的原因不能是' '*cols,更正了。
【解决方案5】:

对于 Python 3,使用 f-String。

from time import sleep
for i in range(61):
    print(f"\r{i}", end="")
    sleep(0.1)

【讨论】:

    【解决方案6】:

    如果您打算从控制台输出中删除某行,

    print "I want to keep this line"
    print "I want to delete this line",
    print "\r " # this is going to delete previous line
    

    print "I want to keep this line"
    print "I want to delete this line\r "
    

    【讨论】:

    • \r 正在打印新的空白行,而不是删除前一行。
    • 通过在最后放置一个分号使上一行不打印换行符,你注意到代码了吗?
    • 尝试在无限的while循环或for循环中编写自己的代码并重复多次,您会看到它正在创建新行。正如标签中提到的那样,我对 python3 是特定的
    • 这不是删除行。它只是将光标移动到行首。除非您写其他内容,否则内容将保留。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多