简体   繁体   English

如何清除 python output 控制台中的最后一行?

[英]How to clear only last one line in python output console?

I am trying to clear only last few line from output console window. To achieve this I have decided to use create stopwatch and I have achieved to interrupt on keyboard interrupt and on enter key press it creates lap but my code only create lap once and my current code is clearing whole output screen.我试图只清除 output 控制台 window 的最后几行。为了实现这一点,我决定使用创建秒表,并且我已经实现了中断键盘中断和按下回车键,它创建了一圈,但我的代码只创建一圈,我的当前代码正在清除整个 output 屏幕。

clear.py清除.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)

when I run当我跑步时

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

in my ipython shell I am able to create only one lap but it is not staying for permanent.在我的 ipython shell 中,我只能创造一圈,但它不会永久停留。

To clear only a single line from the output :从输出中只清除一行:

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

This will clear the preceding line and will place the cursor onto the beginning of the line.这将清除前一行并将光标放在行首。 If you strip the trailing newline then it will shift to the previous line as \033[A means put the cursor one line up如果您去除尾随换行符,则它将移至上一行,因为\033[A表示将光标向上移动一行

I think the simplest way is to use two print() to achieve clean the last line.我认为最简单的方法是使用两个print()来实现清理最后一行。

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

The 1st print() simply make sure the cursor ends at the end of the line and not start a new line第一个print()只是确保光标在行尾结束而不是开始新行

The 2nd print() would move the cursor to the beginning of the same line and not start a new line第二个print()会将光标移动到同一行的开头,而不是开始新行

Then it comes naturally for the 3rd print() which simply start print something where the cursor is currently at.然后它很自然地出现在第三个print()中,它只是开始打印光标当前所在的位置。

I also made a toy function to print progress bar using a loop and time.sleep() , go and check it out我还制作了一个玩具函数来使用循环和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)

The codes shared by Ankush Rathi above this comment are probably correct, except for the use of parenthesis in the print command. Ankush Rathi 在此评论上方共享的代码可能是正确的,除了在 print 命令中使用括号。 I personally recommend doing it like this.我个人建议这样做。

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

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

One thing to keep in mind though is that if you run it in IDLE by pressing F5, the shell will still display both messages.不过要记住的一件事是,如果您在 IDLE 中按 F5 运行它,shell 仍将显示这两条消息。 However, if you run the program by double clicking, the output console will delete it.但是,如果您通过双击运行程序,输出控制台会将其删除。 This might be the misunderstanding that happened with Ankush Rathi's answer (in a previous post).这可能是 Ankush Rathi 的回答(在上一篇文章中)发生的误解。

I know this is a really old question but i couldn't find any good answer at it.我知道这是一个非常古老的问题,但我找不到任何好的答案。 You have to use escape characters.您必须使用转义字符。 Ashish Ghodake suggested to use this Ashish Ghodake 建议使用这个

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

But what if the line you want to remove has more characters than the spaces in the string?但是,如果要删除的行的字符多于字符串中的空格怎么办? I think the better thing is to find out how many characters can fit in one of your terminal's lines and then to add the correspondent number of " " in the escape string like this.我认为最好的办法是找出终端的一行中可以容纳多少个字符,然后像这样在转义字符串中添加对应的“”数。

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

finally I would say that the "function" to remove last line is最后我会说删除最后一行的“功能”是

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

For Python 3's, using f-String.对于 Python 3,使用 f-String。

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

Found a solution on this page that works.此页面上找到了可行的解决方案。 Here is the helper function:这是辅助函数:

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

I hope it helps someone.我希望它可以帮助某人。

None of the other answers worked for me.其他答案都不适合我。 Putting print("Sentence to be overwritten", end='\r') would instantly clear my sentence and it would never be visible to begin with.放置print("Sentence to be overwritten", end='\r')会立即清除我的句子,并且它一开始就永远不可见。 I'm using PyCharm on a Mac if that could be making the difference.我在 Mac 上使用 PyCharm 如果这可能有所作为。 What I had to do is the following:我必须做的是:

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

end='' makes it so the print doesn't automatically put a '\n' character at the end. end=''这样打印就不会自动在末尾放置一个'\n'字符。 Then print("\r", end='') will put the cursor at the beginning of the line.然后print("\r", end='')会将 cursor 放在行首。 Then the 2nd print statement will be printed in the same spot as the first, overwriting it.然后第二个打印语句将打印在与第一个相同的位置,覆盖它。

If you intend to delete certain line from the console output,如果您打算从控制台输出中删除某些行,

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

or或者

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM