2

I keep seeing ways to clear the shell while running a script, however is there a way to clear the screen while running a script in the CMD? My current method works like this:

clear.py

import title
def clear():
    print('\n' * 25)
    title.title()

game.py

from engine import clear
clear.clear()
print(Fore.CYAN + Style.BRIGHT + "--------------------------------")

However this method isn't really reliable as some cmd sizes are different on all computers, nor have I tried it on OSx.

1

2 Answers 2

3

Here's another way, that handles Windows cases as well as Unix-like systems (Linux, OSX, etc.):

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

The clear command works in all Unix-like systems (ie, OSX, Linux, etc.). The Windows equivalent is cls.

Sign up to request clarification or add additional context in comments.

4 Comments

The OP asked specifically for Windows. I gues call(["cls"]) wouldn't work since cls is an internal command of cmd.exe. call("cls", shell=True) would probably work, but what do I know about Windows.
@SvenMarnach I don't see where he asked for Windows. But yes, you'd still call subprocess.call().
"...while running a script in the CMD". I guess that means Windows.
@SvenMarnach True. I've edited my answer. Works on Linux, Mac, and Windows.
3

Your best bet is probably to use the colorama module to enable ANSI escape sequences in the Windows terminal, and then use the ANSI sequence to clear the screen:

import colorama
colorama.init()
print("\033[2J\033[1;1f")

This should work on all common platforms.

5 Comments

In trying to do this, I get the error: AttributeError: 'module' object has no attribute 'COORD'
sgarza62's solution has a different effect from your when done in my interpreter on Ubuntu. Yours leaves a 0 at top left and then my prompt on the next line, his completely clears, but progressively moves my prompt down about two lines, thoughts?
@dawsondiaz: Then your module installation is somehow broken. I can't really help you with that. Try using pip to install modules.
@AaronHall: Your probably got those mixed up. I suspect you are trying this in the interactive interpreter, and the zero you are seeing for sgarza62's solution is the exit code of the command, which is only printed because the interactive pronmpt implicitly prints the results of all expression statements. My code only contained the escape sequence for clearing the screen. I added the code for moving the cursor to the top left corner.
@dawsondiaz It appears what you were seeing is a known bug as per their Google Code bug tracker: Issue 46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.