4

I am trying to get colored command line output. I was able to get colored Python console output using colorama with this:

from colorama import Fore
from colorama import Style

print(f'{Fore.GREEN}A')
print(f'{Fore.RED}B')
print('C')
print(f'{Style.RESET_ALL}D')
print('E')

This perfectly works inside the Python Console in PyCharm. However, if I run the program under Windows cmd. There is no color at all but the colorama text is just added without any effect:

←[32mA
←[31mB
C
←[0mD
E

Can I modify the code so that it also works in Windows cmd?

mrCarnivore
  • 4,638
  • 2
  • 12
  • 29

2 Answers2

4

You'll need to add convert=True to your colorama init call:

from colorama import Fore, Style, init

init(convert=True)

print(f'{Fore.GREEN}A')
print(f'{Fore.RED}B')
print('C')
print(f'{Style.RESET_ALL}D')
print('E')
Jeremiah
  • 623
  • 6
  • 13
  • Thanks. That did indeed work. However, then it does not work in the Python Console any more... Is there a way to detect the environment and then convert or not depending? – mrCarnivore Feb 16 '18 at 13:32
  • You should be able to check `psutil.Process(os.getpid()).parent().name()`. Not sure what the values are for Windows, but it should be something like `"cmd"`. – Jeremiah Feb 16 '18 at 13:40
  • Great! With that I was able to make it work! Thank you! – mrCarnivore Feb 16 '18 at 13:43
  • alternatively you can use `if "started_with_prompt" not in sys.argv:` – WhatsThePoint Feb 19 '18 at 14:23
1

With the help of Jeremiah I was able to make it work in PyCharm and cmd. Here is the complete code:

from colorama import Fore, Style, init
import psutil
import os

if psutil.Process(os.getpid()).parent().name() == 'cmd.exe':
    init(convert=True)

print(f'{Fore.GREEN}A')
print(f'{Fore.RED}B')
print('C')
print(f'{Style.RESET_ALL}D')
print('E')
mrCarnivore
  • 4,638
  • 2
  • 12
  • 29