0

I'm kind of a beginner in Python, and I wanted to highlight some text printed out such as warning, bold whatsoever, using ANSI values.

I found this question (Print in terminal with colors using Python?) in Stack Overflow and I kind of used my own approach:

import sys

def hilite(status, string = ''):
    if sys.stdout.isatty():
                    # Header   # Ok Blue    #Ok Green   # Warning   # Fail      # Bold   # Underline
        attr = ['\033[95m', '\033[94m', '\033[92m', '\033[93m', '\033[91m', '\033[1m', '\033[4m']
        ENDC = '\033[0m'
        print(attr[status]+ string +ENDC)
    else:
        print(string)

# header
hilite(0, '\t\t\t\tMy Python program')

Output:

←[95m                   My Python program←[0m

I tried the original approach but same results. I'm using Windows.

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
mzcoxfde
  • 235
  • 2
  • 13
  • 2
    You're using Windows. Using ANSI escape sequences won't work using the default MS Windows console. – Guillaume Sep 09 '16 at 07:53
  • oh, so is there any way to make it supported or another way of displaying with color? – mzcoxfde Sep 09 '16 at 07:55
  • I'm not a windows specialist so I leave the answer to others. However I strongly suggest using an appropriate existing module like https://pypi.python.org/pypi/colorama instead of reinventing the wheel. – Guillaume Sep 09 '16 at 07:58
  • OK, thanks man. I'll give it a try – mzcoxfde Sep 09 '16 at 08:04
  • Even on Unix/Linux is this code working only on certain types of terminal. Even if it is the most common one, you should never hardcode the escape sequences. See the curses library. https://docs.python.org/3/howto/curses.html – VPfB Sep 09 '16 at 08:40
  • 1
    colorama and termcolor are working good – mzcoxfde Sep 09 '16 at 13:34

0 Answers0