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

Z

zeezlo

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
 
G

Gabriel Genellina

At said:
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.

Yes, just omit the =auto (or use --color=always)
auto means "use colors *only* when *not* redirected"



Gabriel Genellina
Softlab SRL





__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas
 
B

Brett Hoerner

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
 
Z

zeezlo

See the difference? :)

Brett, not only do I see the difference but I actually see it in color,
too! : )

Thanks for your help,

Juerg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top