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

倾然丶 夕夏残阳落幕 提交于 2020-01-15 04:01:46

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/13741873/how-to-get-users-desktop-path-in-python-independent-of-language-install-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!