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

Time:01-12

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

CodePudding user response:

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

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

print(message)
  • Related