7

How can I get to know what my desktop environment is using Python? I like the result to be gnome or KDE or else.

NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104
aliva
  • 5,450
  • 1
  • 33
  • 44

4 Answers4

16

I use this in one of my projects:

    def get_desktop_environment(self):
        #From http://stackoverflow.com/questions/2035657/what-is-my-current-desktop-environment
        # and http://ubuntuforums.org/showthread.php?t=652320
        # and http://ubuntuforums.org/showthread.php?t=652320
        # and http://ubuntuforums.org/showthread.php?t=1139057
        if sys.platform in ["win32", "cygwin"]:
            return "windows"
        elif sys.platform == "darwin":
            return "mac"
        else: #Most likely either a POSIX system or something not much common
            desktop_session = os.environ.get("DESKTOP_SESSION")
            if desktop_session is not None: #easier to match if we doesn't have  to deal with caracter cases
                desktop_session = desktop_session.lower()
                if desktop_session in ["gnome","unity", "cinnamon", "mate", "xfce4", "lxde", "fluxbox", 
                                       "blackbox", "openbox", "icewm", "jwm", "afterstep","trinity", "kde"]:
                    return desktop_session
                ## Special cases ##
                # Canonical sets $DESKTOP_SESSION to Lubuntu rather than LXDE if using LXDE.
                # There is no guarantee that they will not do the same with the other desktop environments.
                elif "xfce" in desktop_session or desktop_session.startswith("xubuntu"):
                    return "xfce4"
                elif desktop_session.startswith('ubuntustudio'):
                    return 'kde'
                elif desktop_session.startswith('ubuntu'):
                    return 'gnome'     
                elif desktop_session.startswith("lubuntu"):
                    return "lxde" 
                elif desktop_session.startswith("kubuntu"): 
                    return "kde" 
                elif desktop_session.startswith("razor"): # e.g. razorkwin
                    return "razor-qt"
                elif desktop_session.startswith("wmaker"): # e.g. wmaker-common
                    return "windowmaker"
            if os.environ.get('KDE_FULL_SESSION') == 'true':
                return "kde"
            elif os.environ.get('GNOME_DESKTOP_SESSION_ID'):
                if not "deprecated" in os.environ.get('GNOME_DESKTOP_SESSION_ID'):
                    return "gnome2"
            #From http://ubuntuforums.org/showthread.php?t=652320
            elif self.is_running("xfce-mcs-manage"):
                return "xfce4"
            elif self.is_running("ksmserver"):
                return "kde"
        return "unknown"

    def is_running(self, process):
        #From http://www.bloggerpolis.com/2011/05/how-to-check-if-a-process-is-running-using-python/
        # and http://richarddingwall.name/2009/06/18/windows-equivalents-of-ps-and-kill-commands/
        try: #Linux/Unix
            s = subprocess.Popen(["ps", "axw"],stdout=subprocess.PIPE)
        except: #Windows
            s = subprocess.Popen(["tasklist", "/v"],stdout=subprocess.PIPE)
        for x in s.stdout:
            if re.search(process, x):
                return True
        return False
Serge Stroobandt
  • 28,495
  • 9
  • 107
  • 102
Martin Hansen
  • 597
  • 6
  • 5
  • 7
    You should make a Python module of it and put it on PyPI. – Jabba Dec 08 '14 at 23:48
  • 4
    I should add that on Ubuntu Studio the `os.environ.get("DESKTOP_SESSION")` throws 'ubuntustudio'. To get the correct Desktop Environment I use `os.environ['XDG_CURRENT_DESKTOP'].lower()` to get 'xfce'. This is a workaround to expand this awesome code. Upload it – DarkXDroid Jul 06 '15 at 13:19
  • 1
    this doesn't work in linux-mint 17.3, keeps returning unknown – answerSeeker Mar 22 '17 at 17:54
  • 1
    @DarkXDroid Ubuntu Studio now uses the Plasma Desktop by KDE. – Serge Stroobandt Jun 08 '22 at 00:31
6

Tested in Ubuntu 9.10:

>>> import os
>>> os.environ.get('DESKTOP_SESSION')
'gnome'

Edit 2: As comments say, this is beginning to be even less reliable with newer GNOME versions. I'm now also running Ubuntu 18.04, and it returns 'ubuntu' instead of the prior 'gnome'.

Edit 1: As mentioned in comments below, this approach will not work for more some OSes. The other two answers provide workarounds.

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
  • Was just in the middle of writing an answer that involved enumerating processes but this is much better. – mdm Jan 10 '10 at 01:12
  • On Mac OS X 10.6.2 `os.environ.get('DESKTOP_SESSION')` returns `"None"` – Daniel Vassallo Jan 10 '10 at 01:16
  • 3
    i think because mac has only one! – aliva Jan 10 '10 at 01:20
  • 1
    On my openSUSE 11.1 system, DESKTOP_SESSION is set to 'default'. – R Samuel Klatchko Jan 10 '10 at 02:20
  • This returns nothing at all for me. Rather, None. I'm using KDE on Ubuntu, but I'm not using a login manager (that is, no KDM or GDM). – JAL Jan 10 '10 at 09:27
  • 1
    Returns 'ubuntu' for me. On Ubuntu 12.04 using stock Unity. Anyone using this method will have to do some testing to find the various responses, not great if your trying to figure out if you want a GTK/QT ui for example. – David C. Bishop Jul 23 '12 at 15:37
  • GNOME can also return `gnome-xorg`, as wayland is now the default, and Ubuntu GNOME desktop may return something different too. – TheKodeToad Nov 24 '21 at 11:13
4

You might try this:

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

And read the discussion here: http://ubuntuforums.org/showthread.php?t=1139057

Leo
  • 37,640
  • 8
  • 75
  • 100
  • That works for my desktop to detect KDE (unlike DESKTOP_SESSION, which returns None) – JAL Jan 10 '10 at 09:28
  • An update on this. Use `xprop -root | grep -io 'xfce'` and then at least alternate between 'xfce' and 'lxde'. This works on Raspbian and Ubuntu Studio. Change output to lower case for better understanding or selection under a statement. – DarkXDroid Jul 06 '15 at 13:49
4

Sometimes people run a mix of desktop environments. Make your app desktop-agnostic using xdg-utils; that means using xdg-open to open a file or url, using xdg-user-dir DOCUMENTS to find the docs folder, xdg-email to send e-mail, and so on.

Tobu
  • 24,771
  • 4
  • 91
  • 98