os.popen output different from native shell output

Nobody nobody at nowhere.com
Tue Aug 25 15:16:23 CEST 2009

On Tue, 25 Aug 2009 01:36:08 -0700, nickname wrote:

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

As others have pointed out, the default behaviour of ls is different if
its output is a terminal.

> 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.

You can get the terminal-style behaviour even when using a pipe with:

	ls -x --color

But why are you reading this information into Python then writing it
back out to the terminal?

If you're planning on processing the output within Python, both the
multi-column format and the escape sequences used for colour will make
such processing awkward.

If you want to enumerate the contents of a directory within Python, use

If you want to generate coloured output, use the curses module, e.g.:

#!/usr/bin/env python

import sys
import curses

setaf = curses.tigetstr('setaf') or ""
setab = curses.tigetstr('setab') or ""
origp = curses.tigetstr('op') or ""

def fg(c):
    sys.stdout.write(curses.tparm(setaf, c))

def bg(c):
    sys.stdout.write(curses.tparm(setab, c))

def orig():

# example
print "hello, world"

More information about the Python-list mailing list