覆盖/清除之前的控制台行 [英] Overwriting/clearing previous console line

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

问题描述

我的问题是,我希望能够覆盖/清除 python 控制台中先前打印的行.这个问题已经被问过很多次了(Python - Remove and Replace Printed items for示例),但是使用相同的代码(答案标记为正确,对我来说根本没有打印出来):

My problem is, that I want to be able to overwrite/clear previous printed line in python console. This question has been asked many times (Python - Remove and Replace Printed items for example), however with the very same code that is (the answer marked as correct, for me prints out nothing at all):

for i in range(10):
    print("Loading" + "." * i)
    time.sleep(1)
    sys.stdout.write("\033[F") # Cursor up one line
    sys.stdout.write("\033[K") # Clear to the end of line

我得到输出(在 python IDLE 中):

I get the output (In python IDLE) :

Loading
[F[KLoading.
[F[KLoading..
[F[KLoading...
[F[KLoading....
[F[KLoading.....
[F[KLoading......
[F[KLoading.......
[F[KLoading........
[F[KLoading.........
[F[KLoading..........
[F[K

有什么想法吗?我用谷歌搜索了很多,没有任何效果.它要么什么也不打印,要么只是不覆盖.

Any ideas? I googled a lot, nothing works really. It either prints out nothing or just does not overwrite.

如果有帮助,我正在运行 Windows 8.1 和 Python 3.51.通过 cmd 运行代码不会影响任何事情.

If that helps, I am running windows 8.1 and Python 3.51. Running the code trough cmd doesn't affect anything.

此外,添加 sys.stdout.flush() 也无济于事.

Also, adding sys.stdout.flush() does not help.

推荐答案

你需要从命令行运行你的程序,而不是从 IDLE 中运行.

You need to run your program form the command line, not from within IDLE.

然后,这应该有效:

import sys
import time

for i in range(10):
    sys.stdout.write("\r" + "Loading" + "." * i)
    time.sleep(1)
    sys.stdout.flush()
print()

\r 转到行首.所以你必须确保你的字符串打印至少和之前的一样长.否则,您将看到之前打印的部分内容.

The \r goes to beginning of the line. So you have to make sure the string you print is at least as long as the one before. Otherwise, you will see parts of the previous print.

这篇关于覆盖/清除之前的控制台行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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