覆盖/清除先前的控制台行

10
我的问题是,我想能够在Python控制台中覆盖/清除先前打印的行。这个问题已经被问了很多次(例如Python - Remove and Replace Printed items),但是用于解决此问题的代码(对我来说被标记为正确的答案)根本没有打印任何内容:
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中获得了输出:

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

有什么想法吗?我在谷歌上搜了很多,但真的没什么用。它要么什么都不打印,要么就是不能覆盖。

如果有帮助的话,我正在运行Windows 8.1和Python 3.51。通过cmd运行代码并不会影响任何东西。

此外,添加sys.stdout.flush()也没有帮助。


你有检查过这个网址吗:https://dev59.com/kobca4cB1Zd3GeqPTT4c - Zorgmorduk
终端必须支持类似 \033[F 的序列 (参见 termcap(3))。据我所知,Windows 对终端功能的支持一直非常差。 - Andrea Corbellini
4个回答

6

你需要在命令行中运行程序,而不是在IDLE中运行。

然后,这个应该可以工作:

import sys
import time

for i in range(10):
    sys.stdout.write("\r" + "Loading" + "." * i)
    time.sleep(1)
    sys.stdout.flush()
print()
< p > \r会回到一行的开头。因此,您必须确保要打印的字符串至少与前一个字符串一样长。否则,您将看到先前打印的部分。


1
对于长度可变的字符串,像 strvar.ljust(10,' ') 这样用空格填充字符串的剩余部分是一个好主意。 - Annarfych
如果打印的行是彩色的,我们也可以应用这个吗? - alper

4

你正在尝试使用ANSI转义序列来移动光标。Windows默认不支持这些序列。为了启用它们,你可以在终端中使用pip install colorama安装colorama模块,然后在Python中:

import colorama
colorama.init()

如果您已经升级到Windows 10,您可以使用以下方法启用支持:
import ctypes
kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)

(来源:https://dev59.com/LFoV5IYBdhLWcg3wCrPH#36760881)

在IT技术中,"RESTful"是指一种架构风格,它建立在HTTP协议之上,用于分布式超媒体系统。"REST"代表"Representational State Transfer",这意味着通过使用HTTP请求来获取和操作资源的状态。这些资源可以是文本、HTML、XML或JSON等格式的数据。RESTful架构的优点包括可伸缩性、灵活性和可移植性。


2

针对Python 3.4以上版本更新的答案

由于print函数具有行结尾和行刷新参数,您可以使用以下方式处理。

text = str()
for i in range(10):
    text = "Loading{}".format("." * i)
    print(text, end="\r", flush=True)
print(" " * len(text), end="\r")

我找不到更优雅的解决方案来清除行末的空格。如果有人知道,请与我分享。

0
否则,如果您只想呈现,可以这样做:
import sys
import time

# point by point
msg = "Loading"

print(msg, end="")

for _ in range(10):
    print(end=".")
    sys.stdout.flush()
    time.sleep(1)
print()

# Or all char by char
i = 10
msg = "Loading" + "." * i

for char in msg:
    print(end=char)
    sys.stdout.flush()
    time.sleep(1)
print()

我希望能够帮助你。谢谢。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接