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

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
alfredodeza
  • 5,058
  • 4
  • 35
  • 44
  • possible duplicate of [How to recognize whether a script is running on a tty?](http://stackoverflow.com/questions/858623/how-to-recognize-whether-a-script-is-running-on-a-tty) – Ignacio Vazquez-Abrams Mar 05 '11 at 02: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). – alfredodeza Mar 05 '11 at 17:09

2 Answers2

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

icktoofay
  • 126,289
  • 21
  • 250
  • 231
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?

Community
  • 1
  • 1
Vlad
  • 9,180
  • 5
  • 48
  • 67
  • 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. – alfredodeza Mar 05 '11 at 02:12