python覆盖上一行 [英] python overwrite previous line

查看:495
本文介绍了python覆盖上一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何覆盖python 2.7中的先前打印内容? 我正在制作一个简单的程序来计算pi.这是代码:

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

基本上经过100000次计算后输出当前pi.如何使它覆盖以前的计算?

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

推荐答案

用回车符'\r'前缀您的输出,并且不要用换行符'\n'结束.这会将光标置于当前行的开头,因此输出将覆盖其先前的内容.用一些尾随空白填充它以确保覆盖.例如

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

使用print照常输出最终值.

我相信这在大多数* nix终端仿真器和Windows控制台中都应该起作用. YMMV,但这是最简单的方法.

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

这篇关于python覆盖上一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆