以下是我正在尝试的代码,如果线路已经通过,我需要在终端上打印绿色如果打印线路出现故障,则需要红色。使用下面的代码完全正常工作。但我希望只有通过和失败应分别打印绿色和红色。不完整的线。请帮忙。
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
答案 0 :(得分:1)
在打印行中的最后一个单词之前(在您的情况下为“通过”或“失败”)之前更改终端颜色,而不是在打印整行之前:
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