2012-03-25 198 views
11

如何覆蓋以前的python 2.7打印? 我正在做一個簡單的程序來計算pi。這裏是代碼:python覆蓋上一行

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)) 

它基本上輸出100000計算後的當前pi。我怎樣才能覆蓋之前的計算?

回答

19

將您的輸出前綴爲回車符號'\r'並且不要以換行符號'\n'結尾。這會將光標置於當前行的開始位置,因此輸出將覆蓋以前的內容。用一些尾隨空格填充以保證覆蓋。例如。

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

像往常一樣用print輸出最終值。

我相信這應該可以在大多數* nix終端仿真器和Windows控制檯中工作。 YMMV,但這是最簡單的方法。

+1

在某些平臺上''\ r''只有‘清除’一個字符(類似的效果,以退格鍵),所以在這種情況下,你將不得不要麼你跟蹤你的大最後一行是和前面加上許多'\ r'字符放入你的下一行,或者更簡單的是總是有一個填充固定長度的輸出(例如使用'str.rjust(...)') – 2012-03-25 14:16:16

+0

thx,這正是我所需要的。 – Cinder 2012-03-25 14:35:20

4

結賬this answer。基本上\r工作正常,但你必須確保你沒有換行符打印。

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

,因爲你每次打印新線這不會工作,\r只是回到以前的換行符。

print語句添加一個逗號會阻止它打印換行符,因此\b將返回到剛剛寫入的行的開頭,並且可以覆蓋它。

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