Reputation: 76
I tried terminal color code using python. But I also want to save it in a file but when I tried to that file is having unreadable text. How can I do this both?
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
def cprint(text, color=WHITE):
seq = "\x1b[1;%dm" % (30+color) + text + "\x1b[0m"
sys.stdout.write(seq)
cprint("String", RED)
It will get a red color output in the terminal. But when I save it into a file it got with color code.
Output in the file:
^[[1;31mstring^[[0m
Upvotes: 0
Views: 647
Reputation: 1725
You could append the text to a file every time you call the function
def cprint(text, file, color=WHITE):
seq = "\x1b[1;%dm" % (30+color) + text + "\x1b[0m"
sys.stdout.write(seq)
with open(file, "a",) as f:
f.write(text)
cprint("String", "/some/file", RED)
Upvotes: 1