tags:

views:

202

answers:

3

Firstly, what is the best/simplest way to detect if X11 is running and available for a python script.

parent process?
session leader?
X environment variables?
other?

Secondly, I would like to have a utility (python script) to present a gui if available, otherwise use a command line backed tool.

Off the top of my head I thought of this

-main python script (detects if gui is available and launches appropriate script)
-gui or command line python script starts
-both use a generic module to do actual work

I am very open to suggestions to simplify this.

+7  A: 

I'd check to see if DISPLAY is set ( this is what C API X11 applications do after all ).

Erik
+2  A: 

You could simply launch the gui part, and catch the exception it raises when X (or any other platform dependent graphics system is not available.

Make sure you really have an interactive terminal before running the text based part. Your process might have been started without a visible terminal, as is common in graphical user environments like KDA, gnome or windows.

Ber
Indeed, this would be my favored approach as well. It's common, too: last I checked, Redhat's Anaconda installer does this too.
ephemient
This was the easiest. I think the DISPLAY answer is good, but the python exceptions will have already happened; depending on where you wanted to try to import. ie import gtk causes an exception if your DISPLAY wasn't set (with my experience). I suppose if you carried enough you could check DISPLAY then do imports for gui libraries. One more plus for DISPLAY is, I feel, based on purest programing practices where exceptions should not handle program logic (if you want to class it as checking DISPLAY as program logic)
rev
+2  A: 

Check the return code of xset -q:

def X_is_running():
    from subprocess import Popen, PIPE
    p = Popen(["xset", "-q"], stdout=PIPE, stderr=PIPE)
    p.communicate()
    return p.returncode == 0

As for the second part of your question, I suggest the following main.py structure:

import common_lib

def gui_main():
    ...

def cli_main():
    ...

def X_is_running():
    ...

if __name__ == '__main__':
    if X_is_running():
        gui_main()
    else:
        cli_main()
codeape