1

I have a simple Python script that uses ANSI escape sequences to have colored output on the terminal.

And this works great, but when the output is being used elsewhere (for example in VIM) all the ANSI sequences show up and it makes it really unreadable.

For example, to display RED I do something like:

^[[91m Errors:
-------^[[0m

Which is perfectly readable in the terminal.

I could add a flag to my Python command line tool to avoid displaying these characters when I need to deal with output, but I was wondering if there is a way of having colored output without messing up output.

The solution would have to use the Python Stdlib or would have to avoid installing a third party library.

However, I am perfectly OK if the approach doesn't work on Windows :)

2
  • possible duplicate of How to recognize whether a script is running on a tty? Commented Mar 5, 2011 at 2:12
  • the question is definitely not a duplicate, but the solution is the same :) People looking (searching) for a problem similar to mine might not know that the answer is the same as the one you are pointing to (since they are different questions). Commented Mar 5, 2011 at 17:09

2 Answers 2

3

You can use os.isatty with the stdout file descriptor, which can be retrieved by calling fileno on sys.stdout.

Edit: It looks like files also have an isatty method; therefore, you can avoid using the os module and just using sys.stdout.isatty().

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

Comments

1

Look at this answer it covers exactly what you are asking for

How do I detect whether sys.stdout is attached to terminal or not?

1 Comment

I think this might be tricky (but I am willing to give it a try). The output comes from VIM's system call and I am not sure it is actually "redirecting" output.

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.