Search code examples
pythonclinuxbashxterm

How to know if the output is going to a terminal or not?


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?


Solution

  • 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.