views:

78

answers:

2

I'm working in Linux and am wondering how to have python tell whether it is being run directly from a terminal or via a GUI (like alt-F2) where output will need to be sent to a window rather than stdout which will appear in a terminal.

In bash, this done by:

if [ -t 0 ] ; then  
    echo "I'm in a terminal"
else
    zenity --info --title "Hello" --text "I'm being run without a terminal"
fi

How can this be accomplished in python? In other words, the equivalent of [ -t 0 ])?

+3  A: 
$ echo ciao | python -c 'import sys; print sys.stdin.isatty()'
False

Of course, your GUI-based IDE might choose to "fool" you by opening a pseudo-terminal instead (you can do it yourself to other programs with pexpect, and, what's sauce for the goose...!-), in which case isatty or any other within-Python approach cannot tell the difference. But the same trick would also "fool" your example bash program (in exactly the same way) so I guess you're aware of that. OTOH, this will make it impossible for the program to accept input via a normal Unix "pipe"!

A more reliable approach might therefore be to explicitly tell the program whether it must output to stdout or where else, e.g. with a command-line flag.

Alex Martelli
There are times when I have used explicit flags while scripting, but at times, I would like an automatic solution understanding under what circumstances it will be needed. I'll still kept this thought for the back burner, though.
narnie
A: 

There are several examples of this on PLEAC which counts for a third case: running at an interactive Python prompt.

Gaius
I have come to like optparse for CL parsing. Do you prefer getopts? If so, I'm curious as to why. I'm new to programming and am eager to learn the why's and wherefore's.
narnie
OptParse *is* better. But getopt works the same in C, Python, Haskell, whatever language you can think of. If you're working in lots of different languages, you may prefer it.
Gaius