How to clear screen using python?

ProgrammingPythonServer Side Programming

To clear the screen while running a python script we have to do something for that because there’s no built-in keyword or function/method to clear the screen. Therefore, we have to write some code.

Clear screen using Python

To clear screen in Python, we can use the os module −

Example

from os import system, name from time import sleep # define our clear function def screen_clear(): if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') # print out some text print('This is a demo line!!!
'
*10) # sleep sleep(2) # now call function we defined above screen_clear()

Output

This is a demo line!!!
This is a demo line!!!
This is a demo line!!!
This is a demo line!!!
This is a demo line!!!
This is a demo line!!!
This is a demo line!!!
This is a demo line!!!
This is a demo line!!!
This is a demo line!!!

Clear screen using Python with the subprocess module

The subprocess module can also be used to clear the screen −

Example

import os from subprocess import call from time import sleep def screen_clear(): _ = call('clear' if os.name =='posix' else 'cls') print('This is a demo line!!!
'
*10) # sleep for 2 seconds after printing output sleep(2) # call the function we defined above screen_clear()

Output

This is a demo line!!!
This is a demo line!!!
This is a demo line!!!
This is a demo line!!!
This is a demo line!!!
This is a demo line!!!
This is a demo line!!!
This is a demo line!!!
This is a demo line!!!
This is a demo line!!!

clear: terminal attributes: No such device or address
raja
Updated on 12-Aug-2022 11:48:03

Advertisements