如何让 powershell 或 windows 终端使用 ansi 转义码打印彩色文本?

问题描述 投票:0回答:2

我正在尝试学习编写Python代码,该代码将使用ansi转义字符在终端中输出不同颜色的文本。我正在观看有关 python 套接字的教程,并且正在学习如何在不同终端之间进行通信。我已经在命令提示符、powershell 和 Windows 终端上尝试了以下操作,结果相同。

message = "$([char]0x1b)[30;41m YOUR_TEXT_HERE $([char]0x1b)[0m"

print(message)

当我尝试此操作时,终端中的输出显示

$([char]0x1b)[30;41m YOUR_TEXT_HERE $([char]0x1b)[0m

我也尝试使用这个,以便双引号在行中

message = "$([char]0x1b)[30;41m YOUR_TEXT_HERE $([char]0x1b)[0m"

print('\"'+message+'\"')

但它只是输出这个

"$([char]0x1b)[30;41m YOUR_TEXT_HERE $([char]0x1b)[0m"

如果我输入

"$([char]0x1b)[30;41m YOUR_TEXT_HERE $([char]0x1b)[0m"
进入终端并按回车键,它显示正确,红色背景和黑色文本

我尝试在谷歌和 YouTube 上搜索此问题,但似乎找不到答案。请帮忙。谢谢

python windows powershell command-prompt ansi-escape
2个回答
2
投票

Python 中的

$([char]0x1b)
应该是
\x1b
。所以这应该有效:

message = "\x1b[30;41m YOUR_TEXT_HERE \x1b[0m"

print(message)

0
投票

Windows Python
(或 Powershell Core)实现中存在一个非常古老的错误,该错误会阻止 ANSI 代码在 Powershell(Core)命令窗口中正确显示。但如果你通过
Windows Terminal
运行它,它就会起作用。

技巧是将 null (

\x00
) 字符发送到终端处理程序以重置任何错误。您可以使用以下方法执行此操作:
import os; os.system('')

python.exe -qu -X utf8=1 -c "import os; os.system(''); m='\n\x1b[30;41m YOUR_TEXT_HERE \x1b[0m\n'; print(m);"

# YOUR_TEXT_HERE

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.