如何仅清除Python输出控制台中的最后一行?

问题描述 投票:0回答:9

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

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 中,我只能创建一圈,但它不会永久保留。

python python-3.x ipython python-3.4
9个回答
12
投票

仅从输出中清除一行:

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

这将清除前一行并将光标置于该行的开头。 如果您删除尾随的换行符,那么它将移动到上一行,因为

\033[A
意味着将光标向上一行


10
投票

我认为最简单的方法是使用两个

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)

8
投票

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

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

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

需要记住的一件事是,如果您通过按 F5 在空闲状态下运行它,shell 仍会显示这两条消息。但是,如果通过双击运行该程序,输出控制台会将其删除。这可能是 Ankush Rathi 的回答(在上一篇文章中)发生的误解。


6
投票

此页面上找到了有效的解决方案。这是辅助函数:

import sys

def delete_last_line():
    "Deletes the last line in the STDOUT"
    # cursor up one line
    sys.stdout.write('\x1b[1A')
    # delete last line
    sys.stdout.write('\x1b[2K')

我希望它对某人有帮助。


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))

1
投票

对于 Python 3,使用 f-String。

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

0
投票

其他答案都不适合我。输入

print("Sentence to be overwritten", end='\r')
会立即清除我的句子,而且它从一开始就永远不可见。我正在 Mac 上使用 PyCharm,如果这能有所作为的话。我必须做的是以下几点:

from time import sleep
print("Sentence to be overwritten", end='')
sleep(1)
print("\r", end='') 
print("Sentence to stay")

end=''
使得打印不会自动在末尾添加
'\n'
字符。然后
print("\r", end='')
会将光标置于行首。然后第二个打印语句将打印在与第一个打印语句相同的位置,覆盖它。


0
投票

您想象的简单解决方案

尽管这是一篇旧帖子,但没有一个答案那么好,并且有一个干净简单的解决方案。这是受到 this post 的启发,但是不需要导入 sys。

如果你想向上一行使用这个:

print("\x1v[1A", end="\r")

要清除您所在的线路,请使用以下命令:

print("\x1v[2K", end="\r")

如果您想清除上一行,请同时使用两者。 如果您只想清除当前所在的行(进度条中经常使用的内容),请仅使用第二个。


-2
投票

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

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 "
© www.soinside.com 2019 - 2024. All rights reserved.