如何清除 Python shell?

pythonserver side programmingprogramming

Python 提供了一个 Python shell,用于执行单个 Python 命令并显示结果。它也被称为 REPL。REPL 代表读取、求值、打印和循环。读取命令,然后求值,之后打印结果并循环回来读取下一个命令。

有时在执行了这么多命令并获得杂乱无章的输出或执行了一些不必要的命令后,我们可能需要清除 Python shell。如果不清除 shell,我们将需要多次滚动屏幕,这是低效的。因此,需要清除 python shell。

用于清除终端或 Python shell 的命令是 cls clear

在 Windows 中

import os
os.system(‘CLS’)

在 Linux 中

import os
os.system(‘clear’)

假设我们需要显示一些输出几秒钟,然后我们想要清除 shell。以下代码可实现此目的。

  • 导入 os 和 sleep

  • 定义一个函数,其中指定清除 shell 的命令,对于 windows 为 cls,对于 linux 为 clear。

  • 打印一些输出

  • 让屏幕休眠几秒钟

  • 调用函数清除屏幕

示例

from os import system, name
from time import sleep
def clear():
   # for windows
   if name == 'nt':
      _ = system('cls')

   # for mac and linux
   else:
   _ = system('clear')

print(“Hi Learner!!”)
sleep(5)
clear()

相关文章