[系統互動篇] 如何在 terminal 中控制輸出位置 - tsungjung411/python-study GitHub Wiki

基本的字元碼資訊

清空畫面

  • Windows
    import os
    os.system("cls") # For Windows
    
  • Linux
    import os
    os.system("clear") # For Linux
    
    或是
    import subprocess
    subprocess.call("clear")
    
    • 連同舊的 log 都被清除,而不是只是將捲軸捲到空白處

透過字元碼控制「清空畫面」

clear = '\x1b[2J\x1b[H'
print(clear)
  • \x1b 表示輸出 ESC 字元
  • [2J 表示清空所有字元,但游標不變
    • If n is 1, clear from cursor to beginning of the screen.
    • If n is 2, clear entire screen
  • [H 將游標移到 (1,1)最上角
    • Moves the cursor to row n, column m.
    • The values are 1-based, and default to 1 (top left corner) if omitted.
  • 參考資料