在很多時候,如果我們在控制台中使用 Python, 隨着時間的推移,可能會發現屏幕越來越亂。
如下圖,我們跑了不少的測試程序,在屏幕上有很多的輸出。
在 Windows 中,我們會使用 cls 命令清屏。
在 Python,應該怎么樣才能清屏呢?
解決
其實 Python 並沒有清屏幕的命令,也沒有內置內置命令可以用。
但是,我們可以使用快捷鍵:
ctrl+l
來進行清屏。
當然,如果你希望使用一個自定義函數的方法來進行清屏。
# -*- coding: utf-8 -*- # import only system from os from os import system, name # import sleep to show output for some time period from time import sleep # define our clear function def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') # print out some text print('Hello CWIKIUS\n' * 10) # sleep for 2 seconds after printing output sleep(2) # now call function we defined above clear()
如上面使用的代碼,我們在運行后,將會看到屏幕在退出前被清理了。