python overwrite previous line
Asked Answered
H

3

12

how do you overwrite the previous print in python 2.7? I am making a simple program to calculate pi. here is the code:

o = 0
hpi = 1.0
i = 1
print "pi calculator"
acc= int(raw_input("enter accuracy:"))
if(acc>999999):
        print "WARNING: this might take a VERY long time. to terminate, press CTRL+Z"
print "precision: " + str(acc)
while i < acc:
        if(o==0):
                hpi *= (1.0+i)/i
                o = 1
        elif(o==1):
                hpi *= i/(1.0+i)
                o = 0
        else:
                print "loop error."
        i += 1
        if i % 100000 == 0:
                print str(hpi*2))
print str(hpi*2))

It basicly outputs the current pi after 100000 calculations. how can I make it overwrite the previous calculation?

Hypoploid answered 25/3, 2012 at 13:55 Comment(0)
A
23

Prefix your output with carriage return symbol '\r' and do not end it with line feed symbol '\n'. This will place cursor at the beginning of the current line, so output will overwrite previous its content. Pad it with some trailing blank space to guarantee overwrite. E.g.

sys.stdout.write('\r' + str(hpi) + ' ' * 20)
sys.stdout.flush() # important

Output the final value as usual with print.

I believe this should work both in most *nix terminal emulators and Windows console. YMMV, but this is the simplest way.

Augite answered 25/3, 2012 at 14:6 Comment(2)
On some platforms '\r' only "erases" one character (similar effect to a backspace key), so in that case you would have to either track you big your last line was and prepend that many '\r' characters into your next line, or more simply just always have a padded fixed length output (e.g. using str.rjust(...) )Stamper
What if there are some previous lines, e.g. when I want to print a matrix?Clambake
C
4

Check out this answer. Basically \r works fine, but you have to make sure you print without the newline characters.

cnt = 0
print str(cnt)
while True:
    cnt += 1
    print "\r" + str(cnt)

This won't work because you print a new line every time, and \r just goes back to the previous newline.

Adding a comma to the print statement will prevent it from printing a newline, so \b will go back to the beginning of the line you just wrote, and you can write over it.

cnt = 0
print str(cnt),
while True:
    cnt += 1
    print "\r" + str(cnt),
Chole answered 27/11, 2014 at 16:29 Comment(0)
O
0
cnt = 0
while True:
    cnt += 1
    print ("\r", cnt, end = " ")

The preceding space (originated by the first ",") is for a more readable output,

Outgoings answered 15/5, 2024 at 17:26 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.