0

What I need to do is the following: in a Python script spawn, say the ls --colors=always / Linux command, and read its output. The important part of this is that I need the output to keep all the ANSI escape sequences (colors and such) to later translate these sequences into HTML. I heard that Python pty module can do that, but I could not find a useful example of its usage in the Internet, and this module's documentation is not quite comprehensive. I'll appreciate if someone could guide me through the way of accomplishing this task.

1 Answer 1

1
import subprocess as sub

process = sub.Popen("ls --colors=always /", stdout=sub.PIPE, stderr=sub.PIPE)
output, errors = process.communicate()

Now all the data you want should be in output - including the ANSI escape sequences.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, this works for 'ls', but for some reason it does not work for Gentoo Linux 'emerge' command, which I actually need. When I call 'emerge -pvuDN world', it just strips all ANSI escapes and returns just plain text.
@Ch00k: I doubt it. Does it work with the color codes for ls? I think emerge is not outputting colors if not used in an interactive shell. Try this: emerge --colory -pvuDN world.
You're right. I need to explicitly pass the '--color y' option to force colors on non-tty outputs. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.