[英]How to clear only last one line in python output console?
我試圖只清除 output 控制台 window 的最后幾行。為了實現這一點,我決定使用創建秒表,並且我已經實現了中斷鍵盤中斷和按下回車鍵,它創建了一圈,但我的代碼只創建一圈,我的當前代碼正在清除整個 output 屏幕。
清除.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 中,我只能創造一圈,但它不會永久停留。
從輸出中只清除一行:
print ("\033[A \033[A")
這將清除前一行並將光標放在行首。 如果您去除尾隨換行符,則它將移至上一行,因為\033[A
表示將光標向上移動一行
我認為最簡單的方法是使用兩個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)
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 的回答(在上一篇文章中)發生的誤解。
我知道這是一個非常古老的問題,但我找不到任何好的答案。 您必須使用轉義字符。 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))
對於 Python 3,使用 f-String。
from time import sleep
for i in range(61):
print(f"\r{i}", end="")
sleep(0.1)
在此頁面上找到了可行的解決方案。 這是輔助函數:
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')
我希望它可以幫助某人。
其他答案都不適合我。 放置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='')
會將 cursor 放在行首。 然后第二個打印語句將打印在與第一個相同的位置,覆蓋它。
如果您打算從控制台輸出中刪除某些行,
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 "
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.