Is there a way of obtaining the Desktop directory path in a cross-platform way, ideally only using standard modules, in Python?
My current Mac OS X + Windows solution is to check which system is running Python with sys.platform and then do the following:
os.path.join(os.path.expanduser('~'), 'Desktop')
.win32com
, or the ctypes-dependent module winpaths; is there a standard alternative?I would be happy with a solution that works on Mac OS X, Windows and Linux.
I used the following:
import os
desktop_file = os.path.expanduser("~/Desktop/myfile.txt")
On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user‘s home directory.
Reference: os.path.expanduser
Underneath windows, the users home is %HOMEPATH%
which is the equivalent of the linux and Mac ~
. Underneath this, there is a folder Desktop
just like on Mac. Python automatically converts ~
to %HOMEPATH% on windows, so your Mac command will work out of the box on Mac and Windows.
On Linux, it's a bit trickier. First, understand that the Linux box you are running on may not have a desktop, so no user desktop folder. If you do have window manager, it may or may not follow the ~\Desktop
paradigm. The wikipedia entry on window managers goes into far more detail, including comparisons between several of the more popular X window managers in some of the sublinks.
Your best bet would be to step back, and ask yourself why do I want/need the users desktop folder? Is it to create a shortcut during the install? You are likely better off with a installation writer utility, such as nsis, handling those details. If it's for file storage, even temporary, you may want to rethink your design. Or are you looking for something, in which case a file system search may be the way to go, instead of a brittle single folder check.
Like most things, it all depends on what you want to accomplish.
As EOL noted in his comment, Windows is slightly trickier than it first appears. His link to a more complete article on the Windows Desktop folder has more details on localization for the desktop folder. This is very important for builders of international applications to take into account, either using automatic localization built into their toolset, or avoiding things that use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With