3

Possible Duplicate:
Detect if stdin is a terminal or pipe in C/C++/Qt?

I want to know if the output of my program is directly going to a terminal or is being redirected to a pipeline or a file.

Because if it goes in the terminal i want to output the escape sequences to make color-text, but on a file or in a pipeline those would not be welcome.

I know it is possible because "ls" does it, anyone knows how?

Community
  • 1
  • 1
LtWorf
  • 7,286
  • 6
  • 31
  • 45
  • 1
    @Douglas: No, that is for C or C++. Just because the python `os` library has a function with the same name and function does not make that question a dupe of this one. There *may* be a python question here on SO already, dupe to that instead. – Martijn Pieters Dec 02 '12 at 13:01
  • I noticed the C tag but not the python tag, sorry about that. (I actually came across [this answer](http://stackoverflow.com/questions/858623/how-to-recognize-whether-a-script-is-running-on-a-tty) while looking for a dupe, but carried on since I was looking for a C one...) – Douglas Dec 02 '12 at 13:04

1 Answers1

6

Use the os.isatty() function on the filedescriptor of the stdout stream or any other file you need to test:

>>> import sys, os
>>> os.isatty(sys.stdout.fileno())
True

For open files (like the sys.stdout stream) the .fileno() method returns the necessary descriptor.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343