Hossein
Hossein

Reputation: 26004

Python text color doesn't work on Windows

I'm trying to get this snippet to work, but it seems it won't work in Windows. Under Linux it works just fine!

Here is the sample snippet of code demonstrating the usage:

        tops = []
        for ind, top in enumerate(lr.top):
            color = colors.setdefault(top, COLORS[len(colors) % len(COLORS)])
            if top in disconnected_tops:
                top = '\033[1;4m' + top
            if len(lr.loss_weight) > 0:
                top = '{} * {}'.format(lr.loss_weight[ind], top)
            tops.append('\033[{}m{}\033[0m'.format(color, top))
        top_str = ', '.join(tops)

When the whole script is run, the escape character seems not to be working and weird characters show up on the screen. How do I get this to work on Windows?

Upvotes: 1

Views: 645

Answers (1)

Hossein
Hossein

Reputation: 26004

I found the problem!
I had to use init() in the script that was missing originally!.
Seems init() is not needed in Linux based OSes!since if it were!, this shouldn't had worked there in first place!
Ok.Here is the documentation itself!:

On Windows, calling init() will filter ANSI escape sequences out of any text sent to stdout or stderr, and replace them with equivalent Win32 calls.

On other platforms, calling init() has no effect (unless you request other optional functionality; see “Init Keyword Args”, below). By design, this permits applications to call init() unconditionally on all platforms, after which ANSI output should just work.

Upvotes: 1

Related Questions