Clear current line in STDOUT in python - python

So I made a program in python that asks a user for input repetitively. After a while, the previous commands start to build up, as so.
> Ping
Pong!
> Hello
Hey there!
>say whats up?
Whats up?
I made the commands up just to show examples
I want to add an animation that adds a ... to the end of a word, such as
i choose.
then clear the line then
i choose..
then clear the line then
i choose...
and so on, but I need to clear the screen in order for this to work and I want the history of the users commands and responses to sill be there. Is there any way using python or importing os to only remove one line instead of the entire screen? Thanks!

You are looking for the carriage return character, \r. When you print that character, the previous line will be cleared. For example:
import time
print('I choose',end='',flush=True)
time.sleep(1)
print('\rI choose.',end='',flush=True)
time.sleep(1)
print('\rI choose..',end='',flush=True)
time.sleep(1)
print('\rI choose...',end='',flush=True)
This is actually how people make the progress bar in command line.

You should be able to do this using normal ‘print’, just appending a comma to the end of the print statement:
from time import sleep
print ‘I choose.’,
sleep(0.5)
print ‘.’,
sleep(0.5)
print ‘.’
Edit: Added in sleeps to make the animation work more as expected.

Related

Want to clear the previous line on terminal in a timer program (python)?

So i have a code of a timer and When a person puts in the number i just want the timer to start and inputted number to not be visible.Code is something like
s=int(input("enter time in sec"))
countdown(s)
so the output is :
enter time in sec 5
0:4
0:3
0:2
0:1
0:0
time up
What i want is to first remove "enter time in sec 5" then when 0:4 prints i want to print 0:3 in its place not below it.
I tried Python deleting input line and copy pasted this on the code like so
s = int(input("enter time in sec "))
print ('\033[1A\033[K')
countdown(s)
and nothing seemed to happen, don't if im wrong in the implementation or it didn't work.
Edit:-
Tried both
os.system('cls')
and
print ('\033[1A\033[K')
neither seemed to work
my code,
def time_format(inp):
import os
m,s=divmod(inp,60)
#os.system('cls')
print ('\033[1A\033[K')
...code for printing time below...
Edit:- im on windows and am using Idle.
neither of the two work
You didn't specify what OS you use but if you target Linux it could
be:
#!/usr/bin/env python3
import time
def countdown(seconds):
for i in range(seconds, -1, -1):
# move to the beginning of the line and remove line
print("\r\033[K", end='', flush=True)
print(f"\r{i}", end='', flush=True)
time.sleep(1)
print("\nTime's up!")
s = int(input("enter time in sec: "))
# move one line up
print("\033[1A", end='', flush=True)
countdown(s)
It works like that:
See accepted answer of: How to clear the interpreter console?
os.system('cls') works on Windows, while
os.system('clear') works on Linux
Got a pop saying I shouldn't delete answered question therefore answering it myself.
I believe both the
print("\033[1A", end='', flush=True)
and
os.system('cls')
works. The issue is that there is no option/method to do it on IDLE. because i tried both the methods work if i double click and run the file as is but none work on IDLE

Making python output print and disappear?

Hey i wanted to know that if there is a way to make a python output print and disappear like in the case of comparing a user entered word with a world in a list,while quickly printing all the words it has traversed ,quite like a animation?
One thing you could try to do is clear the console. There are multiple resources on how to do it so I won't explain it here, but it's easy to find on the internet. If you have a bunch of text in the console and there's a specific piece of text that you want to delete, then you can get all of the text in the console as a string and filter out the part that you want to delete, so that way, when you clear the console, you can re-print that back into the console, so that way it disappears but all of the other text elements do not. If that makes sense lol.
Adding to Amirul Akmal I believe this code might Help you understand it better
from os import system
# import sleep to show output for some time period
from time import sleep
# define our clear function
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
# print out some text
print('test\n'*10)
# sleep for 2 seconds after printing output
sleep(2)
# now call function we defined above
clear()

How to print slowly with a while loop in python 2.7.9

I am trying to print each iteration of the following loop more slowly (so that the person seeing the image printed can actually make out what it is before it goes away too quickly). Any help is welcome. The following code doesn't seem to slow anything down, even when I change the integer to a different number. I don't understand why it's not working.
import time
while True:
print """There are normally 55 lines of strings here, but for readability sake I have deleted them and inserted this text instead."""
time.sleep(5)
Because the call to sleep is outside the while loop, you'll run all the prints, and only then sleep the program.
Indent the call to sleep to include it in your loop.
wrong indentation it should be
import time
while True:
print """There are normally 55 lines of strings here, but for readability sake I have deleted them and inserted this text instead."""
time.sleep(5)

Running a separate function alongside a loop in Python

I am trying to display RSS data on an LED sign using a Raspberry PI. I've based my code on a script that I found for the sign when I first bought it. It's a simple script that allows you to send a message and a colour to the sign and it will scroll across until a keyboard interrupt.
sudo python scroll "Hello World" 1 #red
sudo python scroll "Hello World" 2 #green
sudo python scroll "Hello World" 3 #red and green (orange)
The difference between this script and the one that I am working on is that all the all the data is processed before the loop and then the showmatrix() function is used to show the string on the screen and the shiftmatrix() function is used to scroll the image across.
In order to constantly download the RSS data I have put the following code inside the loop:
#grab emails
newmails = int(feedparser.parse("https://" + USERNAME + ":" + PASSWORD +"#mail.google.com/gmail/feed/atom")["feed"]["fullcount"])
textinput = "You have " + str(newmails) + " new emails"
# append extra characters to text input to allow for wrap-around
textinput+=" :: "
I then use the same functions as before to display this data on the sign:
# Continually output to the display until Ctrl-C
#
# loop around each column in the dotarray
for col in range(len(dotarray[0])):
for row in range(8):
# copy the current dotarray column values to the first column in the matrix
matrix[row][0]=(dotarray[row][col])
# now that we have updated the matrix lets show it
showmatrix()
# shift the matrix left ready for the next column
shiftmatrix()
As the RSS data download takes so long (at last a second), the output loop doesn't run for that time and the sign goes blank. Is there a way of running the feedparser function at the same time so there is no delay?
Am I correct in thinking that multithreading is the way forward? I had a look into couroutines but that got me nowhere.
Yes, os.fork(), youcan make the function run in a different process or the threading module to make it run in another thread.
If the function uses global variables you need to use the threading module and make it run in another thread and if not i'd suggest to do it anyway, less resource wasteful (assuming the function doesnt allocate alot of memory or otherwise uses alot of resources), you code should look something like this:
class displayThread(threading.Thread)
*init function if you need to pass info to the tread, otherwise dont write one but if you do
make sure to call Thread.__init__() first in your function*
def run(): //Overrides the run function
*display what you want on the display*
class downloadThread(threading.Thread)
*init function if you need to pass info to the tread, otherwise dont write one but if you do
make sure to call Thread.__init__() first in your function*
def run(): //Overrides the run function
*download what you want*
and your main script should look like:
thread1 = displayThread
thread2 = downloadThread
thread1.start()
thread2.start()
thread2.join() //waits for download to finish while the display in being updated by the other thread
and if you want to stop the display thread (assuming it goes on forever) you will have to add something like:
os.kill(thread1.getpid(), signal.SIGKILL)
after the .join() and do what you want with the downloaded info.
The multi process version is very similar and you should be able to understand how to make it from my example and the os.fork() docs, if you are having trouble with it - let me know and i'll edit this.

Problems refreshing stdout line using print with python

I've been trying to print out the progress of a for loop in python2.7 using the following code:
for i in range(100):
if float(i) % 10.0 == 0:
print i, "\r",
The behaviour I'm after is the refreshing of the same line on std out rather than writing to a new line every time.
EDIT 1:
Testing in my console (Xfce Terminal 0.4.8), I actually don't get any output regardless of whether I include the if statement or not.
Why is there no output?
I originally said the behaviour of the stdout changed depending on the if statement being there or not because I simplified the code that produced the problem to its most simple form (only to produce the above mentioned effect). My apologies.
EDIT 2:
Thanks to senderle, this is solved. If you miss out the sleep() command, the prints and carriage return happen so quickly you can't see them.
EDIT 3:
One last thing. If you don't catch for the final number in range(100), i.e. 99, the number is cleared off the screen.
EDIT 4:
Note the comma after print i in senderle's answer.
I have found that using sys.stdout is a more system-independent way of doing this, for varions reasons having to do with the way print works. But you have to flush the buffer explicitly, so I put it in a function.
def carriage_return():
sys.stdout.write('\r')
sys.stdout.flush()
This is kind of a WAG. Let me know if it helps.
I tried this and it works for me. The time.sleep is just for dramatization.
import sys, time
def carriage_return():
sys.stdout.write('\r')
sys.stdout.flush()
for i in range(100):
if i % 10 == 0:
print i,
carriage_return()
time.sleep(1)
Finally, I have seen people do this as well. Using terminal control codes like this seems right in some ways, but it also seems more brittle to me. This works for me with the above code as well (on OS X).
def carriage_return():
if sys.platform.lower().startswith('win'):
print '\r'
else:
print chr(27) + '[A'
Testing your code as is, and just including a :colon: at the end of the first line, works just fine with Py2.7 32bit, Windows7 64-bit.
Do you have any out writes to stdout in your if or for block that could be causing the new-lines to be written out ?

Categories