# 如何在 Python 中清屏

**URL:** <https://www.isharkfly.com/t/python/13375>\
**Category:** Python\
**Tags:** python\
**Created:** [March 8, 2021, 4:49am UTC](https://www.isharkfly.com/t/python/13375 "2021-03-08T04:49:26Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [March 8, 2021, 4:49am UTC](https://www.isharkfly.com/t/python/13375/1 "2021-03-08T04:49:26Z")

</div>

在很多时候，如果我们在控制台中使用 Python， 随着时间的推移，可能会发现屏幕越来越乱。

如下图，我们跑了不少的测试程序，在屏幕上有很多的输出。

![python-cls-01](https://www.isharkfly.com/images/transparent.png)

在 Windows 中，我们会使用 cls 命令清屏。

在 Python，应该怎么样才能清屏呢？

## 解决

其实 Python 并没有清屏幕的命令，也没有内置内置命令可以用。

但是，我们可以使用快捷键：

```auto
ctrl+l

```

来进行清屏。

![python-cls-02](https://www.isharkfly.com/images/transparent.png)

当然，如果你希望使用一个自定义函数的方法来进行清屏。

```auto
# -*- 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()

```

如上面使用的代码，我们在运行后，将会看到屏幕在退出前被清理了。
