
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to clear screen using python?
When we work with python interactive shell/terminal, we continuously get the output and the window looks very much clumsy, not to see any output clearly, most of the time we use ctrl+lto clear the screen.
But if we want 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. So, we have to write some code for that.
So, we have to follow some steps
Step 1 − First we have to write from os import system. Step 2 − Next Define a function. Step 3 − Then make a system call with 'clear' in Linux and 'cls' in Windows as an argument. Step 4 − Next we have to store the returned value in an underscore or whatever variable we want (an underscore is used because python shell always stores its last output in an underscore). Step 6 − Lastly call the function.
Example code
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('Hi !! I am Python\n'*10) sleep(2) # now call function we defined above screen_clear()
Output
Hi !! I am Python Hi !! I am Python Hi !! I am Python Hi !! I am Python Hi !! I am Python Hi !! I am Python Hi !! I am Python Hi !! I am Python Hi !! I am Python Hi !! I am Python
Using subprocess module.
Example
import os from subprocess import call from time import sleep def screen_clear(): _ = call('clear' if os.name =='posix' else 'cls') print('Hi !! I am Python\n'*10) # sleep for 2 seconds after printing output sleep(2) # now call the function we defined above screen_clear()
Output
Hi !! I am Python Hi !! I am Python Hi !! I am Python Hi !! I am Python Hi !! I am Python Hi !! I am Python Hi !! I am Python Hi !! I am Python Hi !! I am Python Hi !! I am Python
- Related Questions & Answers
- How to clear screen using C#?
- How to clear screen using Java?
- How to clear screen in python?
- How to print to the Screen using Python?
- How to clear Python shell?
- How to create a Splash Screen using Tkinter?
- How to create a simple screen using Tkinter?
- How can I clear console using C++?
- How to reset or clear a form using JavaScript?
- How to clear an ImageView in Android using Kotlin?
- set clear() in python
- How can I clear text of a textbox using Python Selenium WebDriver?
- How to clear Tkinter Canvas?
- Printing to the Screen in Python
- How to clear the text entered in Selenium with python?
Advertisements