Overwrite previous output on same line - python

I want the output of my code to overwrite the previous output on the same line.
I have read the previous answers to a similar question and have read that I can do this using a ',' and a '\r', but this doesn't seem to work for me. I tried:
for i in range(length):
print 'Minutes:',minute,'of {0}'.format(length),'\r',
minute+=1
time.sleep(1)
But it doesn't print anything other than the last line of the loop. I've tried other arrangements,but nothing yet has worked. Could someone let me know what I'm doing wrong?
Thanks.

If You are doing this in Linux, You can simply use ASCII escape sequence to move cursor up one line (\033[1A). Of course, You will still use \r to move to the beginning of the line. You could use something like this:
for i in range(length):
print('Minutes: ' + minutes + '\033[1A\r')
minutes += 1
sleep(1)

You need sys.stderr for fast output on a screen:
import sys,time
length,minute = 10,0
for i in range(length):
sys.stderr.write('Minutes:{} of {}\r'.format(minute,length))
minute+=1
time.sleep(1)
Don't forget to add sys.stderr.write('\n') at the end of your loop to avoid printing into the same line.

The easiest way I can think of doing this is, if you know how many lines your shell is, then you can just
print "\n" * (number_of_lines - 1)
then
print 'Minutes:',minute,'of {0}'.format(length)
So together,
for i in range(length):
print "\n" * (number_of_lines - 1)
print 'Minutes:',minute,'of {0}'.format(length)
minute += 1
time.sleep(1)
General Tips
You use commas and str.format() in the same print statement, instead just use str.format() for all of it. e.g print 'Minutes: {0}, of {1}'.format(minute, length).
You used minute as your counter even though it appears you are counting by seconds. For clarity you may want to rename that variable second.
Note
sys.stderr is the better way to do this. Please look at rth's answer

If you are using Python3, you can use a code like this:
import time
minute, length = 1, 100
for i in range(length):
print ('Minutes: {0} of {1}\r'.format(minute, length), end = "")
minute+=1
time.sleep(1)
However if you are using Python2, you can import print_function from __future__ module like this example:
from __future__ import print_function
import time
minute, length = 1, 100
for i in range(length):
print("Minutes: {0} of {1}\r".format(minute, length), end = "")
minute+=1
time.sleep(1)
PS: I have a strange issue when running the last code from my terminal using Python2.7.10. The script work but there is not any output.
However within Python 2.7.10 interpreter the code works fine.
Test both solutions and leave your feedbacks if you encounter any problems within Python2.
EDIT:
I think the better solution to avoid the strange issue that i encounter, and i don't know the cause, is using the ASCII escape as #Fejs said in his answer.
Your code will be something like this:
import time
minute, length = 1, 100
for i in range(length):
print "Minutes: {0} of {1} {2}".format(minute, length, '\033[1A\r')
minute+=1
time.sleep(1)

Try flushing the output before each sleep.
minute+=1
sys.stdout.flush()
time.sleep(1)

Related

Python script for core temperature

So I'm writing a little script in python to read the temperature of built-in core sensor(Raspberry Pi) + print it on the screen + write the data to the .txt file. Everything is working pretty much, but I have two problems which I couldn't solve and I have spent like 3-4 hours on it. Fully output of that command is for example: temp=39.0'C and I need only the number from that string --> 39.0. So I'm trying to replace characters and part of the string that I don't need and make it number float.
return temp.replace("temp=", " ").replace("'C", "") My problem is when I'm running this code I still have 1 space before my number and that's because I'm replacing "temp=" with " ", but if I delete that space second replace becomes part of the string and it doesn't do its job anymore, in my opinion, there's too many --> """""'""" of those characters and program gets confused. But how can I solve it? Second problem how can I change it to float because, in my opinion, those numbers are still part of the string? Please help because I am so frustrated that such little script takes so much time to get it working.
import re
import os
import time
def measure_temp():
temp = os.popen("vcgencmd measure_temp").readline()
return temp.replace("temp=", " ").replace("'C", "")
while True:
temperature = measure_temp()
print(temperature)
f = open("pythonLog.txt", "a")
f.write (temperature)
f.close()
time.sleep(1)
Thanks to all who trie to help i have solved by extracting by using temp = temp[1] so the space at the index 0 is gone.

\r in Python does not delete the entire line

i have a quite complex problem, but here is the "simplest version" so you can better understand it.
import time
for i in range(10):
time.sleep(1)
print('{}\r'.format(i), end="")
and here everything works fine, the problem comes when i try to make a countdown
import time
for i in range(10):
time.sleep(1)
print('{}\r'.format(10-i), end="")
the output is 10... then 90... 80... 70 and so on, it seems like if the second cipher of the 10 is not cancelled. can someone tell me why?
\r moves the cursor to the beginning of the line, but it doesn't "clear" anything already printed unless you overwrite it (this may be platform-dependent). Thus, the 0 character will remain visible. You can deal with that by always printing a "fixed-width" column, so that empty spaces are printed to blank out anything left over from before. You can also just put the CR in the end param.
Thus:
import time
for i in range(10):
time.sleep(1)
print('{: <3}'.format(10-i), end='\r')
This uses a format specifier to indicate a space-filled, <left-aligned, 3-width column. You can change the 3 to any higher number depending on how many digits your counter needs.
It's caused by a simple error, you are missing a space before the \r:
Your Code:
print('{}\r'.format(10-i), end="")
# > 10,90,80
Change it to:
print('{} \r'.format(10-i),
#> 10, 9, 8
The issue is like old typewriters when you press \r carriage return it goes to line start and chages one character from there. so 10 will become 90 as the first character changes.
import time
for i in range(10):
time.sleep(1)
print('{:02d}'.format(10-i), end="\r")
So one potential solution is to fix the width. here I have made it 2 digit

How do I type one letter at a time for an input in Python

I recently read about how to type one letter at a time in Python to look old school and cool using loops and time - however, my code has an input. Does anyone know how to do this for and input (in my code , "what is your name?")
I've tried changing the input name but has failed. The code simply prints it at once like usual
If you are looking to do something that looks like this:
Then the easiest way is to do it as it was done back in the good old days. What happened then was that the program would send special codes to the terminal (which back then was a real physical device, not just a window), and the terminal would do whatever codes wanted. There were codes for moving the cursor around, changing colors, beeping and lots of other nifty stuff that you would need.
A common set of codes that still are in use today are known as the ANSI escape codes.
There is an excellent package called Colorama for Python that does all of the heavy-lifting and that is cross-platform. I recommend using that.
Source code for the demo above:
from colorama import init, Fore, Style
import time
def print_old(message):
print(Fore.GREEN, end='', flush=True)
for c in message:
print(c, end='', flush=True)
time.sleep(0.1)
print(Style.RESET_ALL, end='', flush=True)
init()
print_old('What is your name? ')
name = input()
print_old('Nice to meet you %s\n' % name)
Hopefully this is what you are looking for.
This makes it look like what you're talking about
import time
output = "what is your name?"
blank = ""
for i in output:
blank = blank + i
print("\r"+blank, end='')
time.sleep(0.1)
x = input()
The idea is to build larger and larger portions of your output and using the \r you replace the line in the console each time. Waiting 0.1 seconds between loops adds to the effect
If I understand correctly what you are asking, you can print each letter and use input at the end.
Something like this:
output = "what is your name?"
for i in output:
print(i, end='')
x = input()
x will be the string containing what the user inputs.
Imho, it's not cool, just redundant.
If you want a delay between the appearance of each letter, use the time module.
import sys
import time
output = "what is your name?"
for i in output:
print(i, end='')
sys.stdout.flush()
time.sleep(0.1)
x = input()
Note the use of sys.stdout.flush() to push each letter immediately in the output.

print() prints only every second input

I'm new to python and I've been trying to make a little function to call upon when I need to filter an input from everything except regular letters.
I've used SO for parts of the code, but I can't seem to understand why does it only print on every second try.
Here's my code:
import re
i=1
def inputFilterText():
inputRaw = input('input: ')
inputFiltered = re.sub('[^a-zA-Z]+', '', inputRaw)
return inputFiltered
while i > 0:
inputFilterText()
print(inputFilterText())
And here's my output:
I'm not really sure what's going on, but I presume it's a logical error. I've only just started using Python so any help is appreciated.
PSThe 'while' is only there so it's easier to test, it can be omitted.
You are calling inputFilterText twice. Once within the print() and once before. This is causing the code to prompt for input twice before printing the second response.
The problem is that you make a call to the inputFilterText function twice. The first time the output is discarded. Causing input to be taken twice, but only showing a result once.
To fix it, remove the inputFilterText() line. An example of working code.
import re
i=1
def inputFilterText():
inputRaw = input("input: ")
inputFiltered = re.sub(""[^a-zA-Z]+, "", inputRaw)
return inputFiltered
while i > 0:
print(inputFilterText())
Also, in future please send code as raw text, rather than screenshots.
Might I suggest using a variable here, you're not doing anything with the first filter call (this is why it's asking the first time) and the second one you're only printing.
while True:
txt = inputFilterText()
#do some stuff if needed
print(txt)

python: print using carriage return and comma not working

I need to print over one line in a loop (Python 3.x). Looking around on SO already, I put this line in my code:
print('{0} imported\r'.format(tot),)
However, it still prints multiple lines when looped through. I have also tried
sys.stdout.write('{0} imported\r'.format(tot))
but this doesn't print anything to the console...
Anyone know what's going on with this?
If you want to overwrite your last line you need to add \r (character return) and end="" so that you do not go to the next line.
values = range(0, 100)
for i in values:
print ("\rComplete: ", i, "%", end="")
print ("\rComplete: 100%")
In the first case, some systems will treat \r as a newline. In the second case, you didn't flush the line. Try this:
sys.stdout.write('{0} imported\r'.format(tot))
sys.stdout.flush()
Flushing the line isn't necessary on all systems either, as Levon reminds me -- but it's generally a good idea when using \r this way.
I prefer to use the solution of Jan but in this way:
values = range(0, 101)
for i in values:
print ("Complete: ", i, "%", end="\r")
print ()

Categories

Resources