os.popen output different from native shell output

Chris Rebert clp2 at rebertia.com
Tue Aug 25 10:52:55 CEST 2009

On Tue, Aug 25, 2009 at 1:36 AM, nickname<thebiggestbangtheory at gmail.com> wrote:
> Hi all,
>       I am a relative newbie to python, I am using os.popen to run an
> ls command. The output that I get using the read() function is
> different in look and feel from when I run the ls command natively
> from the shell (not via python). I display the ouput via python by
> using the print function on the variable that accepts the os.popen
> ().read() function.
> For example:
> output from native shell (as seen on the bash shell)
> file1 file2 dir1(highlighted in blue color)
> file3longnamewhichwillcausenextfiletoappearonnextline
> file 4
> output from python (as seen on the bash shell)
> file1
> file2
> dir1 (no blue color)
> file3longnamewhichwillcausenextfiletoappearonnextline
> file4
> Is there an easy way to "mirror" the output. When python displays the
> output, how can it tell the bash shell that some of the entries are
> directories and they should appear blue on the bash shell, and that
> everything should not be appearing on 1 column only.

I would assume the difference is caused by `ls` changing behavior (for
example, enabling/disabling colorization) based on whether its output
is going to a terminal or a pipe.

Is there a reason you can't use os.listdir() instead of running ls?:

For the colorization, google for "ANSI color escape sequences"


More information about the Python-list mailing list