
rosuav at gmail
Apr 17, 2012, 7:31 AM
Post #3 of 6
(152 views)
Permalink
|
|
Re: How to determine if IO redirection is occurring with the output from a Python program?
[In reply to]
|
|
On Wed, Apr 18, 2012 at 12:21 AM, Edward d'Auvergne <edward [at] nmr-relax> wrote: > I was wondering if anyone knows of how to detect when IO redirection > of any form is happening within a Python program? I would like to > emulate the behaviour of the GNU tools (for example the Unix commands > 'ls' or 'grep') whereby ascii escape sequences are printed if the > output is solely to the terminal, and in all other cases (redirection > to file via '>', pipes via '|', or more complex redirections) the > ascii escape characters are suppressed. Any ideas would be > appreciated! What you want is the "is-a-TTY" query, which is available in Python as a method on the file-like object: import sys if sys.stdout.isatty(): # True if console, False if redirected # do your fancy escape character stuff Tip: Like the GNU tools, make this only a default. For instance, both ls and grep have an option --color=WHEN where WHEN is either "never", "always", or "auto". If you choose auto (which you can make the default), the tools then check if stdout is a TTY. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
|