478

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.

braX
  • 11,506
  • 5
  • 20
  • 33
Soviut
  • 88,194
  • 49
  • 192
  • 260

31 Answers31

630

As you mentioned, you can do a system call:

For Windows:

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

For Linux it would be:

>>> import os
>>> clear = lambda: os.system('clear')
>>> clear()
Merouane T.
  • 746
  • 1
  • 10
  • 14
Ryan Duffield
  • 18,497
  • 6
  • 40
  • 40
268

here something handy that is a little more cross-platform

import os

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

# now, to clear the screen
cls()
rubenvb
  • 74,642
  • 33
  • 187
  • 332
popcnt
  • 4,519
  • 1
  • 16
  • 14
98

Well, here's a quick hack:

>>> clear = "\n" * 100
>>> print clear
>>> ...do some other stuff...
>>> print clear

Or to save some typing, put this file in your python search path:

# wiper.py
class Wipe(object):
    def __repr__(self):
        return '\n'*1000

wipe = Wipe()

Then you can do this from the interpreter all you like :)

>>> from wiper import wipe
>>> wipe
>>> wipe
>>> wipe
Kenan Banks
  • 207,056
  • 34
  • 155
  • 173
  • 23
    Haha, that's pretty funny. Not exactly what I was looking for, but nice try. – Soviut Feb 05 '09 at 21:23
  • 4
    @Triptych: c = "\n" * 100 usefull, +1 for it. A small comment it clears and brings to the bottom of the shell, i prefer to start from the shell top. – pythonbeginer Sep 20 '11 at 21:02
  • 2
    Or, if your terminal emulator interprets ANSI, better do: `"\x1B[H\x1B[J"` – Alba Mendez Jul 10 '12 at 12:12
  • 9
    Despite people laughing, printing a lot of newlines is exactly what the external processes `clear` and `cls` do. This _is_ the way to do it. (just a print, or a function with the print call, not assigining to a "clear" string, of course) – jsbueno Jun 02 '16 at 05:27
  • It's nice, although you can just scroll up to see the input. – Anonymous Apr 10 '18 at 22:07
  • 10
    @jsbueno no it's not. Well maybe on windows (though I doubt it, it has APIs to clear the console). On all other systems, `clear` outputs a directive that clears the screen. Without trashing the scrollback buffer. On my system, it outputs this control sequence: `\33[3J\33[H\33[2J`. That is: `[erase scrollback]` `[reset cursor position]` `[erase screen]`. The `[erase scrollback]` can be omitted using `clear -x`. – spectras Sep 01 '18 at 11:56
  • 1
    I think the desire is to clear off the text AND put the cursor at the top, left, like a clean, new terminal. Your solution does not do that. Your solution keeps existing text in the scroll buffer. I think the desire is to completely remove the scroll buffer. – Brian Stork Jan 08 '19 at 20:22
  • Though I agree this is a smart thought, the cursor will still be at the bottom of the screen if you clear the console this way. Most of the time I will be clearing the screen to start typing from the top again. – Manu mathew Apr 07 '22 at 04:22
94

This is the simplest thing you can do and it doesn't require any additional libraries. It clears the screen and returns >>> to the top left corner.

print("\033[H\033[J", end="")

UPDATE 1:

Since this answer gets some attention, you might want to know how it works. The command above prints ANSI escape codes:

  • \033 stands for ESC (ANSI value 27).

  • \033[ is a special escape sequence called Control Sequence Introducer (CSI).

  • \033[H command moves the cursor to the top left corner of the screen.

  • \033[J clears the screen from the cursor to the end of the screen.

Optional parameter end="" avoids printing newline character after executing these commands, so >>> stays in the topmost row.

UPDATE 2:

You may want to extend the above command with one additional parameter - x (before J):

print("\033[H\033[xJ", end="")
  • If x is 1, it will clear from cursor to beginning of the screen.
  • If x is 2, it will clear entire screen and move cursor to upper left.
  • If x is 3, it will clear entire screen and delete all lines saved in the scrollback buffer.

So, this command will clear everything, including buffer:

print("\033[H\033[3J", end="")

COMMAND LINE:

To clear screen in a shell (console / terminal) you can use the same command. To clear entire screen and delete all lines saved in the scrollback buffer put 3 before J:

printf "\033[H\033[3J"

or create an alias:

alias cls='printf "\033[H\033[3J"'
Denis Rasulev
  • 3,744
  • 4
  • 33
  • 47
  • 3
    This has the advantage that it also works in Spyder. – Graham G Jun 05 '20 at 10:35
  • 1
    May I ask what is this? – Joe Jan 01 '21 at 12:43
  • 1
    @YoussofH., did you ask about Spyder? If so, then here it is: [Spyder IDE](https://www.spyder-ide.org/) – Denis Rasulev Jan 01 '21 at 19:32
  • 2
    Oh I wasn't clear. I meant `print("\033[H\033[J")` how does this method work, what is it its name!? – Joe Jan 02 '21 at 12:47
  • 1
    Ok, here is the explanation: https://stackoverflow.com/a/55672830/4440387 – Denis Rasulev Jan 03 '21 at 08:45
  • 5
    This one was really the best solution. Simple and multi-platform. – Ahmad Feb 04 '21 at 18:18
  • 5
    This is the only real solution to the problem – throws_exceptions_at_you Mar 19 '21 at 22:19
  • It did not worked for me in win 10 – Valdas Stonkus Nov 06 '21 at 17:34
  • @ValdasStonkus, did you enter it at the Python interpreter invitation ('>>>')? I mean this command is so basic and platform independent that it works anywhere... Also, what was error message you got? – Denis Rasulev Nov 06 '21 at 20:58
  • 1
    I have found this solution to be magnitudes faster – Minek Po1 Dec 05 '21 at 21:01
  • 1
    `\033[H\033[J` only clears the visible screen, exactly the same as the `clear` command up to Ubuntu 18.10. It doesn't clear the scrollback buffer. Scrolling up will reveal the history. To simulate this behavior, insert some terminal lines, then press `Ctrl+L` and insert more. After executing `print("\033[H\033[J", end="")`, only the screen lines inserted after pressing "Ctrl + L" will be deleted. `\033c` clears everything. – Mario Palumbo Jan 26 '22 at 09:29
  • 1
    For completeness, note that this assumes you are connected to a terminal which understands ANSI control codes. There are situations where this isn't true, such as when you are running a pseudo-TTY of some sort, or standard output isn't a terminal at all. Probably at least check for the latter before emitting this, as it tends to generate junk output and new questions on our site. – tripleee Apr 04 '22 at 13:36
  • (TIL that older versions of Windows also don't support proper ANSI codes.) – tripleee Apr 04 '22 at 13:46
  • Good point, @tripleee! I would point to this answer, which might be helpful here: https://stackoverflow.com/a/63913131/4440387 – Denis Rasulev Apr 05 '22 at 06:06
  • What would be the theoretical difference between `\033[H\033[3J` and `\033c`? They both seem to mean "clear everything, delete all scrollback buffer, move cursor to top". What would be the most widely supported sequence? – MestreLion Feb 09 '23 at 04:53
  • See comment from @MarioPalumbo who explains exactly this. – Denis Rasulev Feb 09 '23 at 11:19
  • 2
    doesn't work in IDLE shell – Algoman Mar 01 '23 at 11:47
  • It works perfectly, if I do this in a VSCode Terminal, but if I start Python from a seperate Powershell terminal (PS C:\temp> & "C:\Program Files\Python310\python.exe") and type print("\033[H\033[J", end=""), it prints this in a new line but doesn't clear the screen: ←[H←[J>>> – nadine May 04 '23 at 18:25
  • @nadine, most probably the reason is that those do not support https://en.wikipedia.org/wiki/ANSI_escape_code – Denis Rasulev May 08 '23 at 10:23
49

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()
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
  • 11
    All these ways are pretty... naff. `cls` will only work on windows and make your program hard to be cross platform, printing 100 `newlines` is just... eww? And a keyboard shortcut is not used in the program. – Luke Nov 16 '16 at 09:31
31

Although this is an older question, I thought I'd contribute something summing up what I think were the best of the other answers and add a wrinkle of my own by suggesting that you put these command(s) into a file and set your PYTHONSTARTUP environment variable to point to it. Since I'm on Windows at the moment, it's slightly biased that way, but could easily be slanted some other direction.

Here's some articles I found that describe how to set environment variables on Windows:
    When to use sys.path.append and when modifying %PYTHONPATH% is enough
    How To Manage Environment Variables in Windows XP
    Configuring System and User Environment Variables
    How to Use Global System Environment Variables in Windows

BTW, don't put quotes around the path to the file even if it has spaces in it.

Anyway, here's my take on the code to put in (or add to your existing) Python startup script:

# ==== pythonstartup.py ====

# add something to clear the screen
class cls(object):
    def __repr__(self):
        import os
        os.system('cls' if os.name == 'nt' else 'clear')
        return ''

cls = cls()

# ==== end pythonstartup.py ====

BTW, you can also use @Triptych's __repr__ trick to change exit() into just exit (and ditto for its alias quit):

class exit(object):
    exit = exit # original object
    def __repr__(self):
        self.exit() # call original
        return ''

quit = exit = exit()

Lastly, here's something else that changes the primary interpreter prompt from >>> to cwd+>>>:

class Prompt:
    def __str__(self):
        import os
        return '%s >>> ' % os.getcwd()

import sys
sys.ps1 = Prompt()
del sys
del Prompt
Community
  • 1
  • 1
martineau
  • 119,623
  • 25
  • 170
  • 301
  • This is probably the best answer - a combination of techniques from other answers. PYTHONSTARTUP + __repr__ + os.system('cls'). Very nice. – Kenan Banks Nov 04 '12 at 01:00
  • @Triptych: One interesting side-effect of using `__repr__` and/or `__str__` this way is that if you type `>>> vars()` at the interpreter console, it will execute all the commands thusly defined. On my system, for example, it cleared the screen and then exited the console. Took me a while to figure out what the heck was going on.... – martineau Nov 29 '12 at 19:55
  • interesting. I see this problem also applies to `locals()` and `globals()`. A simple decorator around these functions that deletes the name and reassigns it after function invocation is a possible solution... – Kenan Banks Nov 29 '12 at 21:49
  • @Triptych: The decorator idea doesn't seem to work, at least with my own attempts. Coming up with an viable alternative is proving to surprising difficult. – martineau Nov 29 '12 at 23:31
  • I have a candidate solution that simply munges the result of vars() globals() and locals() calls temporarily: https://gist.github.com/4172781 – Kenan Banks Nov 30 '12 at 00:02
  • @Triptych: Your candidate solution won't work for something like a `vars()` call which is context sensitive because it executes the the built-in one in a different context (inside that of the dynamic function `g()`). It also has the key `'clear'` hardcoded into it which wouldn't apply to `vars`, `locals`, etc. (or even `cls` for that matter). – martineau Jan 21 '14 at 18:15
27

Quickest and easiest way without a doubt is Ctrl+L.

This is the same for OS X on the terminal.

Alex K
  • 8,269
  • 9
  • 39
  • 57
  • 5
    I tried this solution using upper or lowercase "L" with the ctrl key on windows 8.1. It doesn't work for me. I just open and close the shell window to clear it. – Chris22 Jan 11 '16 at 18:27
  • 2
    On OS X, Ctrl+L will pad the terminal until the display is clear. You can still scroll up to see the history. Use Cmd+K to clear the display and printout history. [A more complete list of OS X terminal hotkeys](https://github.com/0nn0/terminal-mac-cheatsheet) – Andrew Franklin Jun 01 '16 at 18:30
20

my way of doing this is to write a function like so:

import os
import subprocess

def clear():
    if os.name in ('nt','dos'):
        subprocess.call("cls")
    elif os.name in ('linux','osx','posix'):
        subprocess.call("clear")
    else:
        print("\n") * 120

then call clear() to clear the screen. this works on windows, osx, linux, bsd... all OSes.

EgMusic
  • 136
  • 17
MartinUbuntu
  • 347
  • 2
  • 5
20

The perfect cls, also compatible with Python2 (in .pythonrc file):

from __future__ import print_function
cls = lambda: print("\033c", end='')

and can be called from the terminal in this way:

cls()

Or directly:

print("\033c", end='')

\033[H\033[J only clears the visible screen, exactly the same as the clear command up to Ubuntu 18.10. It doesn't clear the scrollback buffer. Scrolling up will reveal the history.

To simulate this behavior, insert some terminal lines, then press Ctrl+L and insert more. After executing print("\033[H\033[J", end=""), only the screen lines inserted after pressing "Ctrl + L" will be deleted.

\033c clears everything.

\x1bc may not give the same result as \033c as the hex escape is not clearly length limited.

Mario Palumbo
  • 693
  • 8
  • 32
  • 1
    This should be the accepted and most upvote answer - firstly, it's an overkill IMO to import `os` and run an external command just to get the screen clear, and secondly, it's much faster (this, of course, only matters if you have to do it a zillion times in a row) – TheEagle Jun 30 '21 at 15:47
  • Why are you using *lambda* here? – not2qubit Jan 15 '22 at 12:28
  • Some info on `ESC-c`: *"Triggers a full reset of the terminal to its original state.[20] This may include (if applicable): reset graphic rendition, clear tabulation stops, reset to default font, and more."* – not2qubit Jan 15 '22 at 13:09
  • @not2qubit It is a quick way to implement a function, this short way is not mandatory, the standard one is also excellent. – Mario Palumbo Jan 26 '22 at 09:24
  • Personally I prefer HEX codes and not OCT, so that `ESC = \033 = \x1b`. – not2qubit Jan 26 '22 at 12:47
  • Minor: "\x1bc" may not give the same result as "\033c" as the hex escape is not clearly length limited. – Mario Palumbo Jan 26 '22 at 13:00
  • Ok, I edited the answer for the umpteenth time (hopefully it's the last). – Mario Palumbo Jan 26 '22 at 17:11
  • 1
    Hex escapes with `\x` are by definition always two hex digits long. `\x1b` is perfectly equivalent to `\033`. – tripleee Apr 04 '22 at 13:48
11

I'm not sure if Windows' "shell" supports this, but on Linux:

print "\033[2J"

https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes

In my opinion calling cls with os is a bad idea generally. Imagine if I manage to change the cls or clear command on your system, and you run your script as admin or root.

BuZz
  • 16,318
  • 31
  • 86
  • 141
  • 1
    I agree cls is not ideal in this case, and an ANSI escape sequence is better. In particular using os to invoke a new process is quite a pricy operation, compared to pushing a few bytes to stdout. – silviot Jun 08 '20 at 17:01
10

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()
Pitto
  • 8,229
  • 3
  • 42
  • 51
8

Wiper is cool, good thing about it is I don't have to type '()' around it. Here is slight variation to it

# wiper.py
import os
class Cls(object):
    def __repr__(self):
        os.system('cls')
        return ''

The usage is quite simple:

>>> cls = Cls()
>>> cls # this will clear console.
Amol
  • 85
  • 2
  • 4
  • 1
    I'd name the instance of the `class Cls` to be `cls`. `cls = Cls()` – Amol Dec 27 '11 at 05:47
  • Except that pollutes the initial namespace with two things instead of one...twice as much. – martineau Dec 27 '11 at 19:23
  • @Amol I've used yours and others' techniques in [my solution](https://gist.github.com/3130325). You can do `class cls` and then `cls=cls()`. – Alba Mendez Jul 17 '12 at 16:29
5

Here's the definitive solution that merges all other answers. Features:

  1. You can copy-paste the code into your shell or script.
  2. You can use it as you like:

    >>> clear()
    >>> -clear
    >>> clear  # <- but this will only work on a shell
    
  3. You can import it as a module:

    >>> from clear import clear
    >>> -clear
    
  4. You can call it as a script:

    $ python clear.py
    
  5. It is truly multiplatform; if it can't recognize your system
    (ce, nt, dos or posix) it will fall back to printing blank lines.


You can download the [full] file here: https://gist.github.com/3130325
Or if you are just looking for the code:

class clear:
 def __call__(self):
  import os
  if os.name==('ce','nt','dos'): os.system('cls')
  elif os.name=='posix': os.system('clear')
  else: print('\n'*120)
 def __neg__(self): self()
 def __repr__(self):
  self();return ''

clear=clear()
Alba Mendez
  • 4,432
  • 1
  • 39
  • 55
  • `size = os.get_terminal_size()` and `print('\n' * size.lines, end = '')` (or `shutil.get_terminal_size(fallback=(columns, lines))` to specify a default - 80x24 if not specified) – Dennis Williamson Jul 05 '23 at 14:27
  • The `if` should use `in` instead of `==` for the tuple. And the [docs](https://docs.python.org/3/library/os.html#os.name) don't include `ce` or `dos` but maybe they work in some implementations. – Dennis Williamson Jul 05 '23 at 16:06
4

If it is on mac, then a simple cmd + k should do the trick.

Jagoda Gorus
  • 329
  • 4
  • 18
CoderChai
  • 69
  • 4
4

Use idle. It has many handy features. Ctrl+F6, for example, resets the console. Closing and opening the console are good ways to clear it.

AndyG
  • 39,700
  • 8
  • 109
  • 143
S.Lott
  • 384,516
  • 81
  • 508
  • 779
2

I'm new to python (really really new) and in one of the books I'm reading to get acquainted with the language they teach how to create this little function to clear the console of the visible backlog and past commands and prints:

Open shell / Create new document / Create function as follows:

def clear():
    print('\n' * 50)

Save it inside the lib folder in you python directory (mine is C:\Python33\Lib) Next time you nedd to clear your console just call the function with:

clear()

that's it. PS: you can name you function anyway you want. Iv' seen people using "wiper" "wipe" and variations.

Kirk
  • 16,182
  • 20
  • 80
  • 112
Adriana
  • 37
  • 1
2

just use this..

print '\n'*1000

user1474157
  • 1,379
  • 2
  • 11
  • 13
2

Arch Linux (tested in xfce4-terminal with Python 3):

# Clear or wipe console (terminal):
# Use: clear() or wipe()

import os

def clear():
    os.system('clear')

def wipe():
    os.system("clear && printf '\e[3J'")

... added to ~/.pythonrc

  • clear() clears screen
  • wipe() wipes entire terminal buffer
Victoria Stuart
  • 4,610
  • 2
  • 44
  • 37
2

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()
James Jithin
  • 10,183
  • 5
  • 36
  • 51
userend
  • 1,701
  • 1
  • 13
  • 10
2

How about this for a clear

- os.system('cls')

That is about as short as could be!

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
2

I'm using MINGW/BASH on Windows XP, SP3.

(stick this in .pythonstartup)
# My ctrl-l already kind of worked, but this might help someone else
# leaves prompt at bottom of the window though...
import readline
readline.parse_and_bind('\C-l: clear-screen')

# This works in BASH because I have it in .inputrc as well, but for some
# reason it gets dropped when I go into Python
readline.parse_and_bind('\C-y: kill-whole-line')


I couldn't stand typing 'exit()' anymore and was delighted with martineau's/Triptych's tricks:

I slightly doctored it though (stuck it in .pythonstartup)

class exxxit():
    """Shortcut for exit() function, use 'x' now"""
    quit_now = exit # original object
    def __repr__(self):
        self.quit_now() # call original
x = exxxit()

Py2.7.1>help(x)
Help on instance of exxxit in module __main__:

class exxxit
 |  Shortcut for exit() function, use 'x' now
 |
 |  Methods defined here:
 |
 |  __repr__(self)
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  quit_now = Use exit() or Ctrl-Z plus Return to exit
AAAfarmclub
  • 2,202
  • 1
  • 19
  • 13
2

The OS command clear in Linux and cls in Windows outputs a "magic string" which you can just print. To get the string, execute the command with popen and save it in a variable for later use:

from os import popen
with popen('clear') as f:
    clear = f.read()

print clear

On my machine the string is '\x1b[H\x1b[2J'.

larsr
  • 5,447
  • 19
  • 38
  • 1
    **1)** That magic string is an [ANSI sequence](http://en.wikipedia.org/wiki/ANSI_escape_code). `\x1b[H` means "move the cursor to the top-left corner", `\x1b[2J` means "clear all the screen". **2)** In windows, ANSI is not recognized so probably there isn't any magic string. – Alba Mendez Jul 10 '12 at 12:20
  • 1
    Cool! Also, for python3 print('\x1b[H\x1b[2J', end=''); can help avoid the new line in front. – DenMark Jul 25 '17 at 07:04
  • The magic string worked on Microsoft Windows 10 console with Python 3.6 for me. I plussed for the string sequence not the use of with open. – DevPlayer Feb 02 '19 at 17:38
2
>>> ' '*80*25

UPDATE: 80x25 is unlikely to be the size of console windows, so to get the real console dimensions, use functions from pager module. Python doesn't provide anything similar from core distribution.

>>> from pager import getheight
>>> '\n' * getheight()
anatoly techtonik
  • 19,847
  • 9
  • 124
  • 140
  • That rule is there to avoid simply posting code. It tries to make people **explain** his answer, not just giving code. – Alba Mendez Jul 10 '12 at 12:24
  • It's not a good answer anyway - it's just printing a string of 80*25 spaces... which only works if the console is 2000 characters or smaller (such as 80x25, or 100x20... but the console often winds up 120x50 on my machine. – aramis Jul 17 '12 at 22:34
  • Use http://pypi.python.org/pypi/pager getwidth/getheight to detect console parameters. – anatoly techtonik Jul 18 '12 at 08:43
1

OK, so this is a much less technical answer, but I'm using the Python plugin for Notepad++ and it turns out you can just clear the console manually by right-clicking on it and clicking "clear". Hope this helps someone out there!

guest12345
  • 19
  • 1
1

I found the simplest way is just to close the window and run a module/script to reopen the shell.

Seymour
  • 27
  • 1
1

Magic strings are mentioned above - I believe they come from the terminfo database:

http://www.google.com/?q=x#q=terminfo

http://www.google.com/?q=x#q=tput+command+in+unix

$ tput clear| od -t x1z
0000000 1b 5b 48 1b 5b 32 4a                             >.[H.[2J<
0000007
no ai please
  • 732
  • 3
  • 11
  • 24
tput-guest
  • 19
  • 1
1

I am using Spyder (Python 2.7) and to clean the interpreter console I use either

%clear

that forces the command line to go to the top and I will not see the previous old commands.

or I click "option" on the Console environment and select "Restart kernel" that removes everything.

Youness
  • 11
  • 2
1

EDIT: I've just read "windows", this is for linux users, sorry.


In bash:

#!/bin/bash

while true; do
    clear
    "$@"
    while [ "$input" == "" ]; do
        read -p "Do you want to quit? (y/n): " -n 1 -e input
        if [ "$input" == "y" ]; then
            exit 1
        elif [ "$input" == "n" ]; then
            echo "Ok, keep working ;)"
        fi
    done
    input=""
done

Save it as "whatyouwant.sh", chmod +x it then run:

./whatyouwant.sh python

or something other than python (idle, whatever). This will ask you if you actually want to exit, if not it rerun python (or the command you gave as parameter).

This will clear all, the screen and all the variables/object/anything you created/imported in python.

In python just type exit() when you want to exit.

tripleee
  • 175,061
  • 34
  • 275
  • 318
Andrea Ambu
  • 38,188
  • 14
  • 54
  • 77
1

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
Acorn
  • 49,061
  • 27
  • 133
  • 172
0

Use clear() from replit:

from replit import clear
clear()
JAdel
  • 1,309
  • 1
  • 7
  • 24
-1

If you use vim keybindings in your .inputrc:

set editing-mode vi

It's:

ESC Ctrl-L
Spartan
  • 664
  • 9
  • 12