I'm using Windows 10, Python 3.8. I'm trying to clear everything in my shell, but the code that I'm using doesn't seem to work.
This is my code:
import os
print("Erase This Text")
os.system('cls')
os.system('clear') #This is used for Linux, but I tried it just incase
At my Windows 10 with python 3.8, your code works! Both, cmd and powershell
But you can try some workaround, just printing blank lines, this will lead your cursor to below of your screen and data will be blank, because it will pass cmd height
def cls(height=100):
[print() for _ in range(height)]
But if you want to solve it, the right way, maybe you should check your cmd settings for text encoding.
Related
I am taking input from user in python code. and as per user's provided input I want to clear previous outputs in terminal.
so is there any function? So I can put it in my code.
I searched on internet but it showing me Shortcut keys from keyboard but I want to clear terminal with help of code.(not want to type terminal )
The commands will be slightly different depending on if you're running Python in Windows or Linux/Mac (or a Unix like terminal while in Windows)
In Windows terminals, the command to clear the screen is cls.
In Max/Linux/Unix, the command is clear.
Windows Powershell appears to
except either cls or clear.
To call the appropriate command from within a script, you need to import the os module and call os.system(cmd). This will return a value of 0 for success, so if you are testing it in the terminal directly you may see an extra 0 get displayed on the screen if you don't put the return value into a variable.
Here's some code to call the correct function based on your os. os.name will return 'nt' for Windows or 'posix' for Mac/Linux
import os
# define our clear function
def clear():
# for Windows
if os.name == 'nt':
_ = os.system('cls')
# Mac or Linux (aka posix)
else:
_ = os.system('clear')
Calling the clear() function in your script should clear the terminal as needed.
You can clear the terminal with:
print('\x1b[H\x1b[2J', end='')
...or...
from sys import stdout
stdout.write('\x1b[H\x1b[2J')
...which is probably more efficient than os.system(...)
The string is actually 2 CSI sequences. The first moves the cursor to the screen origin (1, 1). The second sequence is the clear screen directive
I want to know how to refresh the console of my program as if it was just started. Let's say that my code consists of an infinite loop and it has multiple instances of the print() function within itself, I want, every time that loops returns to its start, all the new data whether there is some change or not to get outputted on the same place of the data that has been outputted the last time.
I have been reading about similar problems others have posted and the answers usually revolve around the idea of using \r, when I do that, however, it's always messy and the strings are either printed halfway or there are missing characters. On Replit there is a module called "replit" and there is a function there called clear() that basically performs what I need, but I don't seem to find it when I am using PyCharm, which means that it is perhaps something that works exclusively within the Replit environment. So I am asking, is there something similar in the standard python library that I can use? Thanks
You can use:
import os
command = 'cls' #for windows
os.system(command)
example:
print('hi')
os.system(command)
print('hi')
Output:
hi
For windows you need:
command = 'cls'
For all others it is:
command = 'clear'
To account for any OS you could use:
import os
def clearConsole():
command = 'clear'
if os.name in ('nt', 'dos'): # If computer is running windows use cls
command = 'cls'
os.system(command)
clearConsole()
There is nothing standard in Python to do it, because Python is not aware of whatever console you are using.
When you call print it is actually writing to a file called "standard output".
It can go to a console if you are running your program in a console (like windows cmd, Linux or Mac OS terminal app, or whatever PyCharm uses).
But it can also be redirected to a regular file by the user of your program.
So there is no standard way.
\r is "carriage return" character. On consoles that respect it, it will set your output position to the beginning of the current line, but will not erase any text already printed on that line (usually).
One way to print text in specific places on the screen is PyCurses.
It supports many consoles and figures out which one you are using automatically.
You can do something like this:
import curses
stdscr = curses.initscr()
stdscr.addstr(x, y, "my string")
By using the addstr isntead of print, you can choose the exact position the text will appear, with X and Y coordinates (first two parameters).
Read the documentation for more ways to manipulate text display with this library.
Attempting to use Ctrl+L for clearing Power Sheel in Python 2.7.8 I get no response.
Is there any problem in Windows 10?
Ctrl+L only works on Linux/OS X terminals. It does not work on Windows. To clear the screen on Windows you could do the following:
import os
os.system('cls')
If you're using IDLE on Windows there is not a way to clear it. As a workaround you can use:
print('\n' * 80)
To extend Kredns answer to Linux/OS X terminals as well:
import os
os.system('clear')
I like Kredns's answer, however, you have to type all of that every time.
I made a module/function.
Okay, I am using Python 3.7.3, but similar answer for Python 2.
def cls():
import os
os.system('cls')
return
Save this as a script and import cls or whatever you want to call it. Import that (e.g. on python start up). So if you're in the correct directory:
from cls import cls
Then call it with cls() whenever you want to clear the screen.
cls()
IdleX extension of IDLE has the functionality you are looking for.
Try installing from here
http://idlex.sourceforge.net/
OR
https://pypi.org/project/idlex/
pressing CTRL-L, works in the intutive way (clear the console and take you to the top with a prompt, and doesn't clear the variables and definitions you have defined yet)
Is there anyway of clearing text in IDLE, its really anoying when i run the script a couple of times and then there's a cluster of words which is really hard to read.
and yes I have looked on google, stack_overflow and a couple of more websites but i cant find anything useful.
I tried to do:
import os
def cls():
os.system("cls")
>>>cls()
If you mean using the actual IDLE shell, I don't think there's any way to do it. IDLE is not meant to run programs from, it's just supposed to be a development tool. If you want to run programs from terminal or cmd, you can clear the text easily.
Use this instead:
os.system("clear") # or "cls" on windows
or
subprocess.call('clear') # or "cls" on windows
To fake it in IDLE, you can use something like:
print("\n" * 50)
from subprocess import call as c
def cls():
c("cls",shell=True)
print([x for x in range(10000)])
cls()
Whenever you wish to clear console call the function cls, but note that this function will clear the screen in Windows only if you are running Python Script using cmd prompt, it will not clear the buffer if you running by IDLE.
I am very new to python.. I used the code
x = input(" Hey what is your name " )
print(" Hey, " + x)
input(" press close to exit ")
Because i have looked for this problem on internet and came to know that you have to put some dummy input line at the end to stop the command prompt from getting closed but m still facing the problem.. pls Help
I am using python 3.3
On windows, it's the CMD console that closes, because the Python process exists at the end.
To prevent this, open the console first, then use the command line to run your script. Do this by right-clicking on the folder that contains the script, select Open console here and typing in python scriptname.py in the console.
The alternative is, as you've found out, to postpone the script ending by adding a input() call at the end. This allows the user of the script to choose when the script ends and the console closes.
That can be done with os module. Following is the simple code :
import os
os.system("pause")
This will generate a pause and will ask user to press any key to continue.
[edit: The above method works well for windows os. It seems to give problem with mac (as pointed by ihue, in comments). The thing is that "os" library is operating system specific and some commands might not work with one operating system like they work in another one.]
For Windows Environments:
If you don't want to go to the command prompt (or work in an environment where command prompt is restricted), I think the following solution is gooThe solution I use is to create a bat file.
Use notepad to create a text file. In the file the contents will look something like:
my_python_program.py
pause
Then save the file as "my_python_program.bat" - DO NOT FORGET TO SELECT "All Files!
When you run the bat file it will run the python program and pause at the end to allow you to read the output. Then if you press any key it will close the window.
Just Add Simple input At The End Of Your Program it Worked For Me
input()
Try it And It Will Work Correctly
Try this,
import sys
status='idlelib' in sys.modules
# Put this segment at the end of code
if status==False:
input()
This will only stop console window, not the IDLE.