This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Title: Inconsistent ANSI escape code handling on Windows 10
Type: behavior Stage:
Components: Windows Versions: Python 3.8
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: daverove, paul.moore, steve.dower, tim.golden, zach.ware
Priority: normal Keywords:

Created on 2020-04-01 11:05 by daverove, last changed 2022-04-11 14:59 by admin.

Messages (2)
msg365458 - (view) Author: Dave Rove (daverove) Date: 2020-04-01 11:05
The correct handling of ANSI escape codes by the print() function may or may not be enabled in the Windows 10 command prompt window, depending on previous system calls. The following is quite repeatable. Comment-out the apparently meaningless os.system("") line and ANSI codes do not work, but leave that line in and ANSI codes DO work:

    import os
    os.system("") # Comment this out to disable ANSI codes
    ansi_red = "\x1b[31m"
    ansi_normal = "\x1b[0m"
    print(ansi_red + "This is red!" + ansi_normal)

To be consistent with Python on Linux and Mac, I believe that ANSI codes should be permanently enabled in Windows 10 rather than removed. ANSI code handling was present from the start of Windows 10, so it's reasonable to presume that it's now a permanent feature of the Windows command prompt window. Either way, the inconsistency of the handling should be fixed.

To emphasize that ANSI codes ARE a feature of the command prompt, comment out that line to disable the ANSI codes in print(), but redirect the output to a text file. Then display that file at the command prompt. The ANSI codes then work correctly. 

    python > myansi.txt
    type myansi.txt
msg365492 - (view) Author: Paul Moore (paul.moore) * (Python committer) Date: 2020-04-01 16:15
This works fine for me in Windows terminal, but I see the behaviour described when using the conventional "Command prompt" window.

Enabling ANSI codes is handled via SetConsoleMode (see here: The following proof of concept script correctly displays coloured text:

    from ctypes import *
    kernel32 = windll.kernel32
    kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
    ansi_red = "\x1b[31m"
    ansi_normal = "\x1b[0m"
    print(ansi_red + "This is red!" + ansi_normal)

Agreed this would be worthwhile setting on stdout by default. The code at seems to be an example of how to do this while still supporting older systems
Date User Action Args
2022-04-11 14:59:28adminsetgithub: 84315
2020-04-01 16:15:17paul.mooresetmessages: + msg365492
2020-04-01 11:05:53daverovecreate