Python clear the screen
Asked Answered
M

4

7

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!

Mulberry answered 5/4, 2014 at 19:34 Comment(1)
possible duplicate of clear terminal in pythonTelly
F
5

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.

Frasch answered 5/4, 2014 at 19:54 Comment(0)
E
3

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'])

Eirene answered 18/3, 2017 at 17:7 Comment(2)
I am getting "win32" instead of "windows" what does that mean ?? and whyNaamana
I do not own a Windows computer, however I assume your output is including the API version (en.wikipedia.org/wiki/Windows_API#Versions). I changed the code so that it works with that output.Eirene
M
2

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
Molehill answered 9/8, 2014 at 7:7 Comment(0)
P
2

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.

Pat answered 17/12, 2021 at 0:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.