How to auto-clear console history in python

How can I automatically clear the console history?

It used to be that every time I ran a console-based python program, it would clear everything that was already there and start from a blank screen. But recently Replit had an update and now the console window displays the output from my last several runs. I can clear this history manually by clicking the trash can icon next to the word “Console”, but I’d like to do this automatically.

Seeing the results of old runs is distracting and manually clicking the trash can every time is annoying. How do I automate this?

1 Like

Hey, the previous runs cannot really be cleared automatically, however, they will go away if your current run’s output prints enough lines. So a “solution” would be to print a bunch of newlines so that the previous runs are out of sight. (note that now, printing stuff will start at the bottom, unfortunately).

Near the start of the program, before anything is printed, add this code:

import os
print('\n' * os.get_terminal_size().lines)

Note that clearing the current run’s output is still easily done with something like os.system('clear||cls').

1 Like

Oh interesting idea!

However, @sonicsuns its a “feature” not a bug (heh) that replit has implemented. There is an ongoing request to voice you want the old way back. You can find, and vote for it, here:

1 Like

Pains me so much to see this!

print(end="\033c", flush=True)
1 Like

IIRC, that might not work on Windows. (You can also affect the cursor with ANSI escape codes.)
More discussion:

2 Likes

did more research, Windows 10+ it seems

Support for ANSI Escape Codes was discontinued in Windows after Windows Me and Windows NT, but returned decades later with Windows 10 1511.

UPDATE: I found a way to improve on this method. After you print some newlines, clear the console so that the output starts at the top, and so the run’s output does not have useless newlines.
Note that a single previous run will still show, but it’s just one line at the top.
Python version:

import os
def clear():
  """There are many alternatives to clearing the console, this is just one."""
  os.system('cls' if os.name == 'nt' else 'clear')
print('\n' * os.get_terminal_size().lines)
clear()

...

Please just print the escape codes instead, they’re slightly faster, and don’t depend on the OS.

1 Like

Most consoles support ANSI codes I guess. I heard it can affect cursor too?

If you use the codes for manipulating it, yes.

I use the os.system way (though I don’t really use clear in general) as it is dead simple to understand. I try not to use things I haven’t learned much about, I use them after I learn them.

Pains me to point out that for Windows users this does not clear the console’s History; help that OP was looking for.

First of all, Replit uses a Linux container?
Second of all, NuclearPasta already provided that.

1 Like