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

Brett Hoerner bretthoerner at gmail.com
Wed Sep 27 04:58:29 CEST 2006


zeezlo at yahoo.com wrote:
> child = os.popen("ls --color=auto")
> output = child.read()
>
> results in an output string which is free of the escape sequences
> generated by ls.

Don't use --color=auto,  from the 'ls' man page:

With --color=auto,  color codes are output only if standard output is
connected to a terminal (tty).

'ls' doesn't think Python is a color terminal, so just use "--color",
ie:

>>> import os
>>> a = os.popen("ls --color /")
>>> f = a.read()
>>> f
'\x1b[00m\x1b[00;34mbin\x1b[00m\n\x1b[00;34mboot\x1b[00m\n\x1b[00;34mdev\x1b[00m\n\x1b[00;34metc\x1b[00m\n\x1b[00;34mhome\x1b[00m\n\x1b[00;34mlib\x1b[00m\n\x1b[00;34mlost+found\x1b[00m\n\x1b[00;34mmedia\x1b[00m\n\x1b[00;34mmisc\x1b[00m\n\x1b[00;34mmnt\x1b[00m\n\x1b[00;34mnet\x1b[00m\n\x1b[00;34mopt\x1b[00m\n\x1b[00;34mproc\x1b[00m\n\x1b[00;34mroot\x1b[00m\n\x1b[00;34msbin\x1b[00m\n\x1b[00;34mselinux\x1b[00m\n\x1b[00;34msrv\x1b[00m\n\x1b[00;34msys\x1b[00m\n\x1b[00;34mtmp\x1b[00m\n\x1b[00;34musr\x1b[00m\n\x1b[00;34mvar\x1b[00m\n\x1b[m'
>>> a = os.popen("ls --color=auto /")
>>> f = a.read()
>>> f
'bin\nboot\ndev\netc\nhome\nlib\nlost+found\nmedia\nmisc\nmnt\nnet\nopt\nproc\nroot\nsbin\nselinux\nsrv\nsys\ntmp\nusr\nvar\n'
>>>

See the difference? :)

Brett Hoerner




More information about the Python-list mailing list