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

Viewed 6501

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

5 Answers

In bash I use this script:

$ cat ~/bin/test-term.sh

#!/bin/bash

#See if $TERM has been set when called from Desktop shortcut

echo TERM environment variable: $TERM > ~/Downloads/test-term.txt
echo "Using env | grep TERM output below:" >> ~/Downloads/test-term.txt
env | grep TERM >> ~/Downloads/test-term.txt

exit 0

When you create a desktop shortcut to call the script the output is:

$ cat ~/Downloads/test-term.txt

TERM environment variable: dumb
Using env | grep TERM output below:

Notice grepping env command returns nothing?

Now call the script from the command line:

$ cat ~/Downloads/test-term.txt

TERM environment variable: xterm-256color
Using env | grep TERM output below:
TERM=xterm-256color

This time the TERM variable from env command returns xterm-256color

In Python you can use:

#import os
result = os.popen("echo $TERM")
result2 = os.popen("env | grep TERM")

Then check the results. I haven't done this in python yet but will probably need to soon for my current project. I came here looking for a ready made solution but noone has posted one like this yet.

Related