0

Below is code I am trying and I need to print green color on terminal if line has pass else Red color if print line has fail. This is perfectly working using below code. But I am expecting only pass and fail should print green and red respectively. Not complete line. Please help.

HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
a = [["a", "b", "c", "pass"], ["x", "y", "z", "fail"]]
b = [x for x in a if x is not None]
col_width = max(len(word) for row in b for word in row) + 2  # padding
for row in b:
    if "pass" in row:
        print OKGREEN + ( "".join(word.ljust(col_width) for word in row)) + ENDC
    else:
        print FAIL + ( "".join(word.ljust(col_width) for word in row)) + ENDC
abc
  • 165
  • 2
  • 10
  • You might like [crayons](https://pypi.python.org/pypi/crayons). Looks more convenient. – Reinier Torenbeek Mar 07 '18 at 05:41
  • It's doing what you wrote. The color attribute code is written out, then the big string you created, then the reset. You'll need to bracket the single word you want instead. – Keith Mar 07 '18 at 05:43
  • [You can use termcolor library. View this](https://stackoverflow.com/a/293633/8381371) – SkyLine Mar 07 '18 at 05:44
  • [Colorama](https://pypi.python.org/pypi/colorama) is another library option. tercolor doesn't work on Windows (Colorama does) – Sean Breckenridge Mar 07 '18 at 05:50

1 Answers1

1

Change the terminal color just before printing the last word in a row (in your case 'pass' or 'fail'), not before printing the whole line:

HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
a = [["a", "b", "c", "pass"], ["x", "y", "z", "fail"]]
b = [x for x in a if x is not None]
col_width = max(len(word) for row in b for word in row) + 2  # padding
for row in b:
    if "pass" in row:
        print "".join(word.ljust(col_width) for word in row[:-1]) + OKGREEN + row[-1] + ENDC
    else:
        print "".join(word.ljust(col_width) for word in row[:-1]) + FAIL + row[-1] + ENDC
Piotr Jurkiewicz
  • 1,653
  • 21
  • 25
  • "".join(word.ljust(col_width) for word in row[:-2]) + OKGREEN + row[-2] + END..Last one is not printing .i mean it is printing only a, b c – abc Mar 07 '18 at 08:08