5

I've found several questions and answers to "How do I find the path to the users desktop", but in my mind they are all defunct (those I found at least). The reason is that if the user has a installation of Linux that is not English, he or she may well have the desktop somewhere other than in ~/Desktop. E.g. for Swedish, I believe it is in ~/Skrivbord. And who knows where the user decided to place his or her desktop?

For that reason the following won't do (or any variant of it):

os.sep.join((os.path.expanduser("~"), "Desktop"))

So the question is:

On linux, how do I, in python, get the true path to the user's desktop without presupposing English default directory structure?

deinonychusaur
  • 7,094
  • 3
  • 30
  • 44

2 Answers2

6

Instead of reading directly from the ~/.config/user-dirs.dirs file you can call the xdg-user-dir utility:

import subprocess
subprocess.check_output(['xdg-user-dir', 'DESKTOP'])

This will work with any linux distribution that has a DE which follow the freedesktop specification, which means: KDE, Gnome, XFCE and many more(exactly like the solution already posted by the OP).

Edit:

Updated the subprocess.check_output since arguments need to be in a list. Also worth pointing out that you can change DESKTOP to e.g. DOCUMENTS to get that folder.

deinonychusaur
  • 7,094
  • 3
  • 30
  • 44
Bakuriu
  • 98,325
  • 22
  • 197
  • 231
1

Using @JoachimPileborg's link above: freedesktop.org/wiki/Software/xdg-user-dirs, I put together this code that should safely give the path to the user's desktop if it can be determined:

import os, re
def get_desktop_path():

    D_paths = list()

    try:

        fs = open(os.sep.join((os.path.expanduser("~"), ".config", "user-dirs.dirs")),'r')
        data = fs.read()
        fs.close()
    except:
        data = ""

    D_paths = re.findall(r'XDG_DESKTOP_DIR=\"([^\"]*)', data)

    if len(D_paths) == 1:
        D_path = D_paths[0]
        D_path = re.sub(r'\$HOME', os.path.expanduser("~"), D_path)

    else:
        D_path = os.sep.join((os.path.expanduser("~"), 'Desktop'))

    if os.path.isdir(D_path):
        return D_path
    else:
        return None

It simply tries to parse the file where the users directories should be specified and if that fails it tries to use the English default. Finally it verifies that the directory exists. I admit that the regex-expressions could probably be improved, but I think it should be OK.

deinonychusaur
  • 7,094
  • 3
  • 30
  • 44
  • 1
    Why not a simple `subprocess.check_output('xdg-user-dir')`? This would work on english and non-english linux distributions. For windows you can fall back to join the path and `"Desktop"`. – Bakuriu Dec 06 '12 at 14:15
  • 1
    @Bakuriu, almost right (didn't think of it) but if I understand xdg, what I'm looking for is `xdg-user-dir DESKTOP` – deinonychusaur Dec 06 '12 at 20:17
  • Yes you're right. I didn't remember you had to specify `"Dekstop"` as argument. – Bakuriu Dec 06 '12 at 20:21