Search code examples
pythonwindowspowershellcommand-promptansi-escape

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


Solution

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

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