2017-06-15 661 views
0

我想從輸出控制檯窗口只清除最後幾行。爲了達到這個目的,我決定使用創建秒錶,並且我已經實現了在鍵盤中斷和輸入鍵按下它創建圈,但我的代碼只創建圈一次,我目前的代碼是清除整個輸出屏幕。如何只清除python輸出控制檯中的最後一行?

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) 

,當我在我的IPython shell中運行

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

我可以只創建一個圈,但它沒有停留永久。

回答

0

如果您打算從控制檯輸出刪除某一行,

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 " 
+0

'\ r'正在打印新的空行,而不是刪除前行。 – Gahan

+0

使上一行不要在最後加上分號來打印換行符,您是否注意到代碼中? –

+0

嘗試在無限while循環或for循環中編寫自己的代碼並重復多次,您將看到它正在創建新行。正如標籤中提到的,我對python3有所瞭解 – Gahan