Detecting pipe on stdout?

Alex Martelli aleax at aleax.it
Wed Jul 24 10:36:00 EDT 2002


Alexander Schreiber wrote:

> Hi!
> 
> Is there any way for a Python program to detect wether its stdout has
> been redirected to a pipe/file (like "./programm | less")? I've didn't
> find anything about this in the FAQ and failed to come up with the right
> search terms for google.
> 
> Reason: I've got a Python program[0] here which normally colorizes its
> output (to the terminal) using escape sequences. This is fine and nice
> while running on a terminal, but when running the program with less
> attached to it the escape sequences are annoying. Ideally, I want to
> detect a pipe attached to stdout and switch of the color (the flag is
> already there) in this case.
> 
> Regards,
>       Alex.
> [0] Not written by me.

You probably want os.isatty(sys.stdout.fileno()).  Not quite what
you ask for (it's false whether the redirection is to a pipe OR a
file), but probably what you want.


Alex




More information about the Python-list mailing list