I would like my application to store some data for access by all users. Using Python, how can I find where the data should go?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
From http://snipplr.com/view.php?codeview&id=7354
To get the app-data directory for all users, rather than the current user, just use
shellcon.CSIDL_COMMON_APPDATA
instead ofshellcon.CSIDL_APPDATA
.Since SHGetFolderPath is deprecated, you can also use SHGetKnownFolderPath in Vista and newer. This also lets you look up more paths than SHGetFolderPath will. Here's a stripped-down example (full code available on Gist):
You can access all of your OS environment variables using the
os.environ
dictionary in theos
module. Choosing which key to use from that dictionary could be tricky, though. In particular, you should remain aware of internationalized (i.e., non-English) versions of Windows when using these paths.os.environ['ALLUSERSPROFILE']
should give you the root directory for all users on the computer, but after that be careful not to hard code subdirectory names like "Application Data," because these directories don't exist on non-English versions of Windows. For that matter, you may want to do some research on what versions of Windows you can expect to have the ALLUSERSPROFILE environment variable set (I don't know myself -- it may be universal).My XP machine here has a COMMONAPPDATA environment variable which points to the All Users\Application Data folder, but my Win2K3 system does not have this environment variable.
Previous answer removed due to incompatibility with non-US versions of Windows, and Vista.
EDIT: To expand on Out Into Space's answer, you would use the
winpaths.get_common_appdata
function. You can get winpaths usingeasy_install winpaths
or by going to the pypi page, http://pypi.python.org/pypi/winpaths/, and downloading the .exe installer.Take a look at http://ginstrom.com/code/winpaths.html. This is a simple module that will retrieve Windows folder information. The module implements
get_common_appdata
to get the App Data folder for all users.If you don't want to add a dependency for a third-party module like winpaths, I would recommend using the environment variables already available in Windows:
Specifically you probably want
ALLUSERSPROFILE
to get the location of the common user profile folder, which is where the Application Data directory resides.e.g.:
EDIT: Looking at the winpaths module, it's using ctypes so if you wanted to just use the relevant part of the code without installing winpath, you can use this (obviously some error checking omitted for brevity).
Example run: