Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get users desktop path in python independent of language install (linux)

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?

like image 723
deinonychusaur Avatar asked Dec 06 '12 10:12

deinonychusaur


1 Answers

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.

like image 199
Bakuriu Avatar answered Sep 23 '22 06:09

Bakuriu