Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if python script is being run in a terminal or via GUI?

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 ])?

like image 979
narnie Avatar asked Sep 29 '10 03:09

narnie


People also ask

Is Python CLI or GUI?

Most Python codes are written as scripts and command-line interfaces (CLI).

Does Python run in terminal?

A widely used way to run Python code is through an interactive session. To start a Python interactive session, just open a command-line or terminal and then type in python , or python3 depending on your Python installation, and then hit Enter .

How do I run a Python file in GUI?

Use Tkinter to Create a GUI If you're new to creating GUI's in Python the basic steps are to: Import the Tkinter module: import Tkinter, top = Tkinter.Tk() Create the GUI main window that will “house” your GUI and widgets. Add whatever widgets your GUI needs including buttons, labels, lists etc.


2 Answers

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

like image 153
Alex Martelli Avatar answered Oct 22 '22 11:10

Alex Martelli


I scoured SE for an answer to this but everywhere indicated the use of sys.stdout.isatty() or os.isatty(sys.stdout.fileno()). Neither of these dependably caught my GUI test cases.

Testing standard input was the only thing that worked for me:

sys.stdin.isatty()
like image 31
Six Avatar answered Oct 22 '22 11:10

Six