如何在 python 中清除螢幕?


在 Python 中我們有時會連結輸出,而我們想清除單元格提示符的螢幕,我們可以透過按 Control + l 來清除螢幕。但有時候我們需要根據程式的輸出量和我們希望如何格式化輸出,以程式設計方式清除螢幕。在這種情況下,我們需要在 Python 指令碼中放置一些命令,以便在程式需要時清除螢幕。

我們需要從 Python 的 OS 模組中獲取 system() 來清除螢幕。對於不同平臺(如 Windows 和 Linux),我們需要傳遞不同的命令,如以下示例所示。我們還使用“_”變數,用於儲存直譯器中最後表示式的值。

示例

import os
from time import sleep
# The screen clear function
def screen_clear():
   # for mac and linux(here, os.name is 'posix')
   if os.name == 'posix':
      _ = os.system('clear')
   else:
      # for windows platfrom
      _ = os.system('cls')
   # print out some text
print("The platform is: ", os.name)
print("big output\n"* 5)
# wait for 5 seconds to clear screen
sleep(5)
# now call function we defined above
screen_clear()

輸出

執行以上程式碼會給出以下結果 −

The platform is: nt
big output
big output
big output
big output
big output

在結果視窗中的 5 秒後,上述輸出會被清除。

更新於:08-8月-2019

6K+ 次檢視

開啟你的 職業 生涯

透過完成課程獲得認證

開始
廣告