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())

- 14,636
- 4
- 35
- 55

- 538
- 1
- 4
- 15
-
1See: http://stackoverflow.com/questions/2356391/why-does-supplying-stdin-to-subprocess-popen-cause-what-is-written-to-stdout-to – Stephen Rauch Mar 03 '17 at 22:50
-
1Possible duplicate of [Why does supplying stdin to subprocess.Popen cause what is written to stdout to change?](http://stackoverflow.com/questions/2356391/why-does-supplying-stdin-to-subprocess-popen-cause-what-is-written-to-stdout-to) – Nic Mar 03 '17 at 23:22
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.

- 14,636
- 4
- 35
- 55
-
Thank you. I don't quit understand this sentence "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". Do you mean escape the ANSI color code? – Herbert Mar 06 '17 at 17:36
-
@Herbert -- If you are taking the output of the process and writing it to a terminal, and you want to see the color output, you would want the escape codes included. – antlersoft Mar 06 '17 at 17:48
-
1The subprocess is a tcl script. I tried it with open the subprocess with stdout = sys.stdout instead of stdout = PIPE. This makes it preserve the color. I don't think I'm able to change how the print function in tcl behaves. So can you show me a link to how to direct output to a virtual terminal. Thanks. – Herbert Mar 06 '17 at 22:44
-
1@Herbert - The Tcl way to do that is with expect; there is a python module called pexpect that should do the same thing. I don't know more details than that, though. pexpect.readthedocs.io – antlersoft Mar 07 '17 at 17:21