[英]python overwrite previous line
你如何覆蓋python 2.7中的先前打印? 我正在制作一個簡單的程序來計算pi。 這是代碼:
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。 如何讓它覆蓋以前的計算?
前綴您的輸出與回車符'\\r'
和不換行符號結束吧'\\n'
。 這會將光標放在當前行的開頭,因此輸出將覆蓋其先前的內容。 用一些尾隨空格填充它以保證覆蓋。 例如
sys.stdout.write('\r' + str(hpi) + ' ' * 20)
sys.stdout.flush() # important
像往常一樣輸出最終值與print
。
我相信這應該適用於大多數* nix終端模擬器和Windows控制台。 YMMV,但這是最簡單的方法。
看看這個答案 。 基本上\\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),
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.