Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python clear the screen

I am still trying to make my quiz, but I want to enter a clear the screen code for my questions. So, after researching, I found a code that works, but it puts my questions way to the bottom of the screen. Here is a screenshot I took:

The Image is below

here is a example of the clear the screen code I found:

print "\n" * 40

So I tried changing the "40" To "20" but there was no effects. I am operating on Mac so the

import os
os.system('blahblah')

does not work. Please help!

like image 397
boatofturtles Avatar asked Apr 05 '14 19:04

boatofturtles


4 Answers

As @pNre noted, this question shows you how to do this with ASCI escape sequences.

If you'd like to do this using the os module, then on Mac the command is clear.

import os
os.system('clear')

Note: The fact that you are on a Mac does not mean os.system('blahblah') will not work. It is more likely the command you are passing to os.system was erroneous.

See answer below for how to do this on Windows/Linux.

like image 93
jaynp Avatar answered Nov 13 '22 23:11

jaynp


This function works in any OS (Unix, Linux, OS X, and Windows)
Python 2 and Python 3

from platform   import system as system_name  # Returns the system/OS name
from subprocess import call   as system_call  # Execute a shell command

def clear_screen():
    """
    Clears the terminal screen.
    """
    
    # Clear screen command as function of OS
    command = 'cls' if system_name().lower().startswith('win') else 'clear'

    # Action
    system_call([command])

In windows the command is cls, in unix-like systems the command is clear.
platform.system() returns the platform name. Ex. 'Darwin' in macOS.
subprocess.call() performs a system call. Ex. subprocess.call(['ls','-l'])

like image 41
ePi272314 Avatar answered Nov 13 '22 23:11

ePi272314


Can be done by subprocess

import subprocess as sp

clear_the_screen = sp.call('cls', shell=True) # Windows <br>
clear_the_screen = sp.call('clear', shell=True) # Linux
like image 2
Earth Defender Avatar answered Nov 13 '22 23:11

Earth Defender


Best OSX solution for Python (No need to import any modules), simply do:

print("\033c\033[3J")

Or in Terminal for bash/shell script use:

echo -n "\033c\033[3J"

Or:

printf "\033c\033[3J"

Do NOT use clear command!

In OSX if you use command: clear then you will still be able to scroll back in Terminal window so it will not help to save/clear memory.

like image 1
Cyborg Avatar answered Nov 13 '22 22:11

Cyborg