python overwrite previous line

拈花ヽ惹草 提交于 2019-11-30 18:11:04

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.

Anubian Noob

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),
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!