Desktop session detection python

As, i was doing a bug fix for this bug i had to find a way to detect the current desktop session, based on which further changes had to made, so i did something like :

def startNewSession(self):
         sessionType = os.environ.get('DESKTOP_SESSION')
         if options.development_mode and sessionType == "gnome":
             logging.getLogger().debug('Switching X user')
             subprocess.Popen(["gdmflexiserver"," -xnest"])
         if sessionType == "gnome":
             logging.getLogger().debug('Logging user out')
             subprocess.Popen(["gnome-session-save", "--logout"])
         if sessionType == "kde":
             logging.getLogger().debug('Logging user out')
             os.system("dbus-send --session --dest=org.kde.ksmserver /KSMServer org.kde.KSMServerInterface.saveCurrentSession")
             os.system("qdbus org.kde.ksmserver /KSMServer logout 0 0 0")
         else:
             info = getoutput('xprop -root _DT_SAVE_MODE')
             if ' = "xfce4"' in info:
                 subprocess.Popen(["xfce4-session-logout", "--logout"])

But later i was found that os.environ.get('DESKTOP_SESSION') returns 'default' for pure KDE, that is if there is no GDM along with others, the issue was clear that GDM was setting the $DESKTOP_SESSION variable and in the absence of it the value would remain 'default' which would void the further logic!

Luckily after further probing into better method of doing it, the solution was pretty clear with the os.environ.get() was the right method of choice, but it needed more better param to be passed to indeed get more stabler returns! As per the main logic goes :

def detect_desktop_environment():
    desktop_environment = 'generic'
    if os.environ.get('KDE_FULL_SESSION') == 'true':
        desktop_environment = 'kde'
    elif os.environ.get('GNOME_DESKTOP_SESSION_ID'):
        desktop_environment = 'gnome'
    else:
        try:
            info = getoutput('xprop -root _DT_SAVE_MODE')
            if ' = "xfce4"' in info:
                desktop_environment = 'xfce'
        except (OSError, RuntimeError):
            pass
    return desktop_environment
Share this