删除命令中的多行打印 ASCII 控制字符
deleting multiple lines in command prints ASCII control chars
使用 Python 3.7,我试图在命令 window (Windows 10 - cmd) 中重写多行输出。对于单行来说很简单,因为我可以使用回车 return.
再次打印该行
print('\r only once',end='')
print('\r only once',end='')
但是,如果有多行,这将不起作用。现在我尝试使用 ascii 控制字符来做到这一点。这通常在一个循环中完成以显示进度,但一个最小的例子是
import os
import sys
import time
print("upper") #moves back in line
print("lower") #moves back in line
#time.sleep(1)
#os.system("pause")
sys.stdout.write("3[K") #clear line
sys.stdout.write("3[F") #back to previous line
sys.stdout.write("3[K") #clear line
sys.stdout.write("3[F") #back to previous line
sys.stdout.write("3[K") #clear line
sys.stdout.write("3[F") #back to previous line
print("new upper") #moves back in line
print("new lower") #moves back in line
如果它像这样运行或 time.sleep(1)
未注释,则输出为:
upper
lower
[K[F[K[F[K[Fnew upper
new lower
如果 os.system("pause")
(仅限 windows)未注释,则输出正确
new upper
new upper
有谁知道,为什么 os.system("pause")
会更改控制字符的行为或通常如何启用它们?或者,是否有人对如何替换 python?
的多行输出有其他(或什至更好)的想法
您正在尝试使用 ANSI 转义序列,windows 至少在默认情况下不支持。
我听说您可以使用 Colorama 来启用这些,安装后在程序开头执行以下操作:
import colorama
colorama.init()
@Tylerr 回答有效。但是我刚刚发现,如果您在周年更新后拥有 Win 10(版本 1607、02.08.2016,目前大多数 Win 10 用户可能已经拥有),您可以通过添加或更改 [=] 来启用 cmd.exe 的本机支持13=]VirtualTerminalLevel 注册表如图所示 here
我今天遇到了同样的问题。我在 Win10 Pro 1903.
我最终下载了 Windows 终端,它解决了我所有的问题! (https://www.microsoft.com/en-us/p/windows-terminal/9n0dx20hk701)
ANSI 转义字符(如“\x1b[1A”)现在可用!
在 PowerShell 之前:
ANSI PowerShell fail
PS。示例来自:Is there a way to clear your printed text in python?
但在 Windows 终端中,它有效!
使用 Python 3.7,我试图在命令 window (Windows 10 - cmd) 中重写多行输出。对于单行来说很简单,因为我可以使用回车 return.
再次打印该行print('\r only once',end='')
print('\r only once',end='')
但是,如果有多行,这将不起作用。现在我尝试使用 ascii 控制字符来做到这一点。这通常在一个循环中完成以显示进度,但一个最小的例子是
import os
import sys
import time
print("upper") #moves back in line
print("lower") #moves back in line
#time.sleep(1)
#os.system("pause")
sys.stdout.write("3[K") #clear line
sys.stdout.write("3[F") #back to previous line
sys.stdout.write("3[K") #clear line
sys.stdout.write("3[F") #back to previous line
sys.stdout.write("3[K") #clear line
sys.stdout.write("3[F") #back to previous line
print("new upper") #moves back in line
print("new lower") #moves back in line
如果它像这样运行或 time.sleep(1)
未注释,则输出为:
upper
lower
[K[F[K[F[K[Fnew upper
new lower
如果 os.system("pause")
(仅限 windows)未注释,则输出正确
new upper
new upper
有谁知道,为什么 os.system("pause")
会更改控制字符的行为或通常如何启用它们?或者,是否有人对如何替换 python?
您正在尝试使用 ANSI 转义序列,windows 至少在默认情况下不支持。
我听说您可以使用 Colorama 来启用这些,安装后在程序开头执行以下操作:
import colorama
colorama.init()
@Tylerr 回答有效。但是我刚刚发现,如果您在周年更新后拥有 Win 10(版本 1607、02.08.2016,目前大多数 Win 10 用户可能已经拥有),您可以通过添加或更改 [=] 来启用 cmd.exe 的本机支持13=]VirtualTerminalLevel 注册表如图所示 here
我今天遇到了同样的问题。我在 Win10 Pro 1903.
我最终下载了 Windows 终端,它解决了我所有的问题! (https://www.microsoft.com/en-us/p/windows-terminal/9n0dx20hk701)
ANSI 转义字符(如“\x1b[1A”)现在可用!
在 PowerShell 之前: ANSI PowerShell fail
PS。示例来自:Is there a way to clear your printed text in python?
但在 Windows 终端中,它有效!