Ystan
Ystan

Reputation: 117

How do I get powershell or windows terminal to print color text using ansi escape codes?

I'm trying to learn to write python code that will output in the terminal different colour text using ansi escape characters. I'm watching a tutorial on python sockets and just learning to communicate between different terminals. I've tried the following on command prompt, powershell and windows terminal and same results.

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

print(message)

When I try this, the output in the terminal shows

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

I also tried to use this so that the double quotes were in the line

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

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

but it just outputs this

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

If I type "$([char]0x1b)[30;41m YOUR_TEXT_HERE $([char]0x1b)[0m" into the terminal and press enter, it shows correct with red background and black text

I've tried to google and youtube about this but can't seem to find an answer. Please help. Thanks

Upvotes: 3

Views: 1228

Answers (2)

not2qubit
not2qubit

Reputation: 16912

There is a very old bug in the Windows Python (or Powershell Core?) implementation that prevents ANSI escape codes from being displayed properly in the Powershell (Core) command window. But if you run this through Windows Terminal it works.

If you still want to use the default Powershell command window, you can trick it, by sending a null (\x00) character to the terminal handler, to reset whatever is wrong. You can do this using: 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


PS. It would make sense to file a bug report to the Powershell Repo.

Upvotes: 1

Roj
Roj

Reputation: 1342

The $([char]0x1b) should be \x1b in Python. So this should work:

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

print(message)

Upvotes: 2

Related Questions