Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ANSI color lost when using python subprocess [closed]

I'm trying to run a process within another python process. The program I run normally has colored output when run in an ANSI terminal emulator. When I have my controlling python program print the output from the sub-process, I don't see any color. The color from the subprocess is lost when I read from it and print to screen. print(subp.stdout.readline())

like image 276
Herbert Avatar asked Mar 03 '17 22:03

Herbert


1 Answers

Processes that produce color output do it by sending escape codes to the terminal(-emulator) intermixed with the output. Programs that handle the output of these programs as data would be confused by the escape codes, so most programs that produce color output on terminals do so only when they are writing to a terminal device. If the program's standard output is connected to a pipe rather than a terminal device, they don't produce the escape codes. When Python reads the output of a sub-process, it does it through a pipe, so the program you are calling in a sub-process is not outputting escape codes.

If all you are doing with the output is sending it to a terminal, you might want the escape codes so the color is preserved. It's possible that your program has a command-line switch to output escape codes regardless of the output device. If it does not, you might run your sub-process against a virtual terminal device instead of a pipe to have it output escape codes; which is too complex a topic to delve into in this answer.

like image 83
antlersoft Avatar answered Sep 21 '22 14:09

antlersoft