0

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

6
  • Possible duplicate of How to print to console in color? Commented Nov 3, 2017 at 10:36
  • @Hackaholic Read my question again understand the problem I am facing. Commented Nov 3, 2017 at 10:39
  • Why can't you write the unmodified text to the file? Commented Nov 3, 2017 at 10:44
  • In this case when you're printing on console then only apply color codes while writing in file only include string/text you want to log. Commented Nov 3, 2017 at 10:45
  • @MaheshKaria But the problem is both processes are in same way first it will print and save it to a log file. Commented Nov 3, 2017 at 10:50

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.