有時使用 Python shell 時,我們會得到隨意的輸出或編寫不必要的語句,出於某些其他原因,我們想要清除屏幕。
「cls」和「clear」命令用於清除終端(終端窗口)。如果,你使用的是 IDLE 內的 shell,不會受到這類事情的影響。遺憾的是,在 IDLE 中沒有辦法清除屏幕。你能做的最好的事情就是將屏幕向下滾動很多行。
例如-
print("/n" * 100)
雖然你可以把它放在一個函數中:
def cls():
print("/n" * 100)
然後在需要時作為 cls()函數調用它。它將清除控制台;所有先前的命令將消失,屏幕從頭開始。
如果你使用的是 Linux ,那麼-
Import os
# Type
os.system('clear')
如果你使用的是窗口
Import os
#Type
os.system('CLS')
我們也可以使用 Python 腳本來實現。考慮下面的例子。
示例-
# import os module
from os import system, name
# sleep module to display output for some time period
from time import sleep
# define the 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\n'*10)
# sleep time 2 seconds after printing output
sleep(5)
# now call function we defined above
clear()
注意-使用下劃線變數是因為 Python shell 總是將其最後的輸出存儲在下劃線中。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/233592.html