'Python clear terminal without using system calls

I would like to write a python script for use on Windows and Linux that clears the screen.
Most of the examples for this are something like:

import os
os.system('cls')

which works, but is a bit dicey given all of the issues with making system calls (security issues). Is there a better way of clearing the terminal in python without needing to use system?
The best alternative I have found so far was this:

print("\033c");

but it has the slight annoyance of removing everything from the terminal
(ie I would like it to clear the terminal, but the user should be able to scroll up and see previous output in the terminal).



Solution 1:[1]

The following ANSI escape code should help on linux (and most *nix unless you find a really weird terminal):

print("\x1b[2J\x1b[H",end="")

It'll clear the screen and put your cursor at the top left. You can still scroll up to find your old stuff but you may have to go up a decent distance to find it.

I have absolutely no idea what it'll do on windows. You may find you need to detect the os and use a different method there.

For python 2.x you'll need to use sys.stdout.write instead of the print statement as you can't suppress the \n on print in 2.x as far as I know.

Solution 2:[2]

If you have special knowledge of the screen size you can use a modified version of your original print-based answer.

def cls(x):
    """Clears the screen after printing x newlines."""
    print "\n" * x
    print "\033c"

In Python 3.3 and later you can divine the size of the Terminal window with shutil, but I don't think there's a great way to do it in 2.7 without actually importing os, which you said should be avoided.

Solution 3:[3]

This piece of code doesn't call os directly from the code.
Try this:

from subprocess import call
def clear(int=None):  
    call('clear')
    if int == 0:
       exit()
clear()

It worked for me, I work on linux but I think it will work on windows to.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 or1426
Solution 2
Solution 3 Guy Goldenberg