DEV Community

Abel Orban
Abel Orban

Posted on

A way to enable ANSI escape sequences in the Windows virtual terminal using Python

One of the projects that I'm currently working on is an implementation of the classic Spider Solitaire game that is played in the console, made using Python.

To make the output easier on the eyes, I intended to change the colour of a few details using escape sequences, as I've used them before. During my first test to see if I managed to format the output correctly, I was surprised to see the sequences in string format:

←[90mXX←[97m ←[90mXX←[97m ←[90mXX←[97m ←[90mXX←[97m ←[90mXX←[97m
Enter fullscreen mode Exit fullscreen mode

This was even more surprising as I had already implemented 2048 in a similar way, in the console, and it was working fine.

After some digging, I found out that while the Windows terminal supports ANSI escape sequences, this feature isn't enabled by default. You have to enable it from within the application, something which is pretty easily done in Python as well.

I was still wondering why it was working in the 2048 implementation but not in this project, and I managed to figure it out after some inspection. I still hadn't implemented cleaning the screen in Spider Solitaire, which I did with the os module:

Enter fullscreen mode Exit fullscreen mode

Or, since I was planning on porting it to Linux anyway, as little effort as that may require with Python:

os.system("cls" if == "nt" else "clear")
Enter fullscreen mode Exit fullscreen mode

Suddenly, the output was coloured:

the result

I had to implement clearing the screen anyway, but I never expected that this little bit of code had such an overarching effect.

I'm not sure if Microsoft knows of this, as their page about clearing the console screen also includes enabling the escape sequences. It may just be the overconfidence of youth talking, though.

To check that it wasn't some background Python magic I wrote a small C++ program to check:

#include <iostream>
#include <windows.h>

int main() {
    std::cout << "\033[31mHello, red\033[97m" << std::endl;
    return 0;
Enter fullscreen mode Exit fullscreen mode

Lo, and behold, without system("cls"), it outputs all the characters, but with it, only the short text in the desired red colour:

It may have something to do with the fact that I'm still using Windows 10, even though I doubt it, but it is an interesting and odd observation nonetheless.

Thanks for reading!

Top comments (0)