How to clear the interpreter console?

2018-12-31 08:56发布

Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.

Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.

I've heard about doing a system call and either calling cls on Windows or clear on Linux, but I was hoping there was something I could command the interpreter itself to do.

Note: I'm running on Windows, so Ctrl+L doesn't work.

30条回答
大哥的爱人
2楼-- · 2018-12-31 09:05

As you mentioned, you can do a system call:

For Windows

>>> import os
>>> clear = lambda: os.system('cls')
>>> clear()

For Linux the lambda becomes

>>> clear = lambda: os.system('clear')
查看更多
永恒的永恒
3楼-- · 2018-12-31 09:05

You have number of ways doing it on Windows:

1. Using Keyboard shortcut:

Press CTRL + L

2. Using system invoke method:

import os
cls = lambda: os.system('cls')
cls()

3. Using new line print 100 times:

cls = lambda: print('\n'*100)
cls()
查看更多
旧时光的记忆
4楼-- · 2018-12-31 09:08

Here's a cross platform (Windows / Linux / Mac / Probably others that you can add in the if check) version snippet I made combining information found in this question:

import os
clear = lambda: os.system('cls' if os.name=='nt' else 'clear')
clear()

Same idea but with a spoon of syntactic sugar:

import subprocess   
clear = lambda: subprocess.call('cls||clear', shell=True)
clear()
查看更多
谁念西风独自凉
5楼-- · 2018-12-31 09:08

How about this for a clear

- os.system('cls')

That is about as short as could be!

查看更多
旧时光的记忆
6楼-- · 2018-12-31 09:09

Here are two nice ways of doing that:

1.

import os

# Clear Windows command prompt.
if (os.name in ('ce', 'nt', 'dos')):
    os.system('cls')

# Clear the Linux terminal.
elif ('posix' in os.name):
    os.system('clear')

2.

import os

def clear():
    if os.name == 'posix':
        os.system('clear')

    elif os.name in ('ce', 'nt', 'dos'):
        os.system('cls')


clear()
查看更多
谁念西风独自凉
7楼-- · 2018-12-31 09:10

This should be cross platform, and also uses the preferred subprocess.call instead of os.system as per the os.system docs. Should work in Python >= 2.4.

import subprocess
import os

if os.name == 'nt':
    def clearscreen():
        subprocess.call("cls", shell=True)
        return
else:
    def clearscreen():
        subprocess.call("clear", shell=True)
        return
查看更多
登录 后发表回答