DEV Community

Onorio Catenacci
Onorio Catenacci

Posted on

A Handy Way To Clear The Terminal In Python

So I have been using the Python REPL quite a bit lately. I've been using it on Windows and it was really getting quite annoying to me that I couldn't clear the terminal screen.

With a little bit of work I was able to hack together this code to allow me to clear the terminal. There were a few small issues that made this non-trivial.

Running CLS

Most of the examples I could find on StackOverflow used os.cmd to call either clear or cls. Using os.system is deprecated. I needed to figure out how to run this as a subprocess. This made it slightly more tricky because cls is an internal command. That means it's built into the cmd executable. We can't execute cls directly therefore we need to execute it as part of an invocation of cmd.

The command line is cmd /c cls. The /c parameter tells the command processor to immediately exit after executing the cls.

import subprocess

def clear() -> None:
    command = ['cmd']
    args = ['/c','cls']
    cli = command + args
    subprocess.run(cli) 
    return None
Enter fullscreen mode Exit fullscreen mode

Making Clear Available Automatically

So while we have the right code now we want it to automatically be available to us every time we fire up a Python REPL clear is available to us.

It's my understanding that there are multiple ways to stash this code so that Python picks it up automatically. Here's how I did it.

I created a new User Level Environment Variable PYTHONSTARTUP and pointed it to my %USERPROFILE% directory. USERPROFILE is the Windows analog of the HOME directory on a *nix machine. I saved the code in a .pyrc file which I stored into the %PYTHONSTARTUP% directory.

This is nothing major or earthshaking but it took me a few minutes of work to figure it out so I thought others might like to know about it as well.

Top comments (0)