preserving color ouput of a shell command via os.popen()

Jean-Paul Calderone exarkun at divmod.com
Wed Sep 27 05:35:18 CEST 2006


On 26 Sep 2006 19:07:54 -0700, zeezlo at yahoo.com wrote:
>Hi everyone
>
>I would like to get the output of a shell process on Linux (eg, "ls
>--color=auto") run via os.popen(), filter it and then output parts of
>it while preserving any original coloring added by that process.
>
>Doing
>
>child = os.popen("ls --color=auto")
>output = child.read()
>
>results in an output string which is free of the escape sequences
>generated by ls.
>
>Is there a way to preserve them when I capture whatever the processes
>writes to stdout? I could add them manually (or use curses), but then I
>would just be duplicating the work done by ls.
>
>Thanks in advance
>
>Juergen
>

To ls, --color=auto indicates that the type of the output file descriptor
should be detected and colors included or elided depending on whether it
is likely that the output is being viewed by a human or a program.

Since you are running ls with popen, ls decides it is a program, and elides
the colors.

Try os.popen("ls --color=yes").

Jean-Paul



More information about the Python-list mailing list