gooderp18绿色标准版
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

494 line
19KB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright (c) 2005-2010 ActiveState Software Inc.
  4. # Copyright (c) 2013 Eddy Petrișor
  5. """Utilities for determining application-specific dirs.
  6. See <http://github.com/ActiveState/appdirs> for details and usage.
  7. """
  8. from __future__ import print_function
  9. # Dev Notes:
  10. # - MSDN on where to store app data files:
  11. # http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120
  12. # - Mac OS X: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html
  13. # - XDG spec for Un*x: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
  14. __version_info__ = (1, 3, 0)
  15. __version__ = '.'.join(str(v) for v in __version_info__)
  16. import sys
  17. import os
  18. def user_data_dir(appname=None, appauthor=None, version=None, roaming=False):
  19. r"""Return full path to the user-specific data dir for this application.
  20. "appname" is the name of application.
  21. If None, just the system directory is returned.
  22. "appauthor" (only required and used on Windows) is the name of the
  23. appauthor or distributing body for this application. Typically
  24. it is the owning company name. This falls back to appname.
  25. "version" is an optional version path element to append to the
  26. path. You might want to use this if you want multiple versions
  27. of your app to be able to run independently. If used, this
  28. would typically be "<major>.<minor>".
  29. Only applied when appname is present.
  30. "roaming" (boolean, default False) can be set True to use the Windows
  31. roaming appdata directory. That means that for users on a Windows
  32. network setup for roaming profiles, this user data will be
  33. sync'd on login. See
  34. <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
  35. for a discussion of issues.
  36. Typical user data directories are:
  37. Mac OS X: ~/Library/Application Support/<AppName>
  38. Unix: ~/.local/share/<AppName> # or in $XDG_DATA_HOME, if defined
  39. Win XP (not roaming): C:\Documents and Settings\<username>\Application Data\<AppAuthor>\<AppName>
  40. Win XP (roaming): C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>
  41. Win 7 (not roaming): C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>
  42. Win 7 (roaming): C:\Users\<username>\AppData\Roaming\<AppAuthor>\<AppName>
  43. For Unix, we follow the XDG spec and support $XDG_DATA_HOME.
  44. That means, by default "~/.local/share/<AppName>".
  45. """
  46. if sys.platform == "win32":
  47. if appauthor is None:
  48. appauthor = appname
  49. const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA"
  50. path = os.path.normpath(_get_win_folder(const))
  51. if appname:
  52. path = os.path.join(path, appauthor, appname)
  53. elif sys.platform == 'darwin':
  54. path = os.path.expanduser('~/Library/Application Support/')
  55. if appname:
  56. path = os.path.join(path, appname)
  57. else:
  58. path = os.getenv('XDG_DATA_HOME', os.path.expanduser("~/.local/share"))
  59. if appname:
  60. path = os.path.join(path, appname)
  61. if appname and version:
  62. path = os.path.join(path, version)
  63. return path
  64. def site_data_dir(appname=None, appauthor=None, version=None, multipath=False):
  65. r"""Return full path to the user-shared data dir for this application.
  66. "appname" is the name of application.
  67. If None, just the system directory is returned.
  68. "appauthor" (only required and used on Windows) is the name of the
  69. appauthor or distributing body for this application. Typically
  70. it is the owning company name. This falls back to appname.
  71. "version" is an optional version path element to append to the
  72. path. You might want to use this if you want multiple versions
  73. of your app to be able to run independently. If used, this
  74. would typically be "<major>.<minor>".
  75. Only applied when appname is present.
  76. "multipath" is an optional parameter only applicable to \*nix
  77. which indicates that the entire list of data dirs should be
  78. returned. By default, the first item from XDG_DATA_DIRS is
  79. returned, or :samp:`/usr/local/share/{AppName}`,
  80. if ``XDG_DATA_DIRS`` is not set
  81. Typical user data directories are:
  82. Mac OS X
  83. :samp:`/Library/Application Support/{AppName}`
  84. Unix
  85. :samp:`/usr/local/share/{AppName}` or :samp:`/usr/share/{AppName}`
  86. Win XP
  87. :samp:`C:\Documents and Settings\All Users\Application Data\{AppAuthor}\{AppName}`
  88. Vista
  89. Fail! "C:\ProgramData" is a hidden *system* directory on Vista.
  90. Win 7
  91. :samp:`C:\ProgramData\{AppAuthor}\{AppName}` (hidden, but writeable on Win 7)
  92. For Unix, this is using the ``$XDG_DATA_DIRS[0]`` default.
  93. WARNING: Do not use this on Windows. See the Vista-Fail note above for why.
  94. """
  95. if sys.platform == "win32":
  96. if appauthor is None:
  97. appauthor = appname
  98. path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA"))
  99. if appname:
  100. path = os.path.join(path, appauthor, appname)
  101. elif sys.platform == 'darwin':
  102. path = os.path.expanduser('/Library/Application Support')
  103. if appname:
  104. path = os.path.join(path, appname)
  105. else:
  106. # XDG default for $XDG_DATA_DIRS
  107. # only first, if multipath is False
  108. path = os.getenv('XDG_DATA_DIRS',
  109. os.pathsep.join(['/usr/local/share', '/usr/share']))
  110. pathlist = [ os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep) ]
  111. if appname:
  112. if version:
  113. appname = os.path.join(appname, version)
  114. pathlist = [ os.sep.join([x, appname]) for x in pathlist ]
  115. if multipath:
  116. path = os.pathsep.join(pathlist)
  117. else:
  118. path = pathlist[0]
  119. return path
  120. if appname and version:
  121. path = os.path.join(path, version)
  122. return path
  123. def user_config_dir(appname=None, appauthor=None, version=None, roaming=False):
  124. """Return full path to the user-specific config dir for this application.
  125. "appname" is the name of application.
  126. If None, just the system directory is returned.
  127. "appauthor" (only required and used on Windows) is the name of the
  128. appauthor or distributing body for this application. Typically
  129. it is the owning company name. This falls back to appname.
  130. "version" is an optional version path element to append to the
  131. path. You might want to use this if you want multiple versions
  132. of your app to be able to run independently. If used, this
  133. would typically be "<major>.<minor>".
  134. Only applied when appname is present.
  135. "roaming" (boolean, default False) can be set True to use the Windows
  136. roaming appdata directory. That means that for users on a Windows
  137. network setup for roaming profiles, this user data will be
  138. sync'd on login. See `managing roaming user data
  139. <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>`_
  140. for a discussion of issues.
  141. Typical user data directories are:
  142. Mac OS X
  143. same as user_data_dir
  144. Unix
  145. :samp:`~/.config/{AppName}` or in $XDG_CONFIG_HOME, if defined
  146. Win *
  147. same as user_data_dir
  148. For Unix, we follow the XDG spec and support ``$XDG_DATA_HOME``.
  149. That means, by default :samp:`~/.local/share/{AppName}`.
  150. """
  151. if sys.platform in [ "win32", "darwin" ]:
  152. path = user_data_dir(appname, appauthor, None, roaming)
  153. else:
  154. path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config"))
  155. if appname:
  156. path = os.path.join(path, appname)
  157. if appname and version:
  158. path = os.path.join(path, version)
  159. return path
  160. def site_config_dir(appname=None, appauthor=None, version=None, multipath=False):
  161. r"""Return full path to the user-shared data dir for this application.
  162. "appname" is the name of application.
  163. If None, just the system directory is returned.
  164. "appauthor" (only required and used on Windows) is the name of the
  165. appauthor or distributing body for this application. Typically
  166. it is the owning company name. This falls back to appname.
  167. "version" is an optional version path element to append to the
  168. path. You might want to use this if you want multiple versions
  169. of your app to be able to run independently. If used, this
  170. would typically be "<major>.<minor>".
  171. Only applied when appname is present.
  172. "multipath" is an optional parameter only applicable to \*nix
  173. which indicates that the entire list of config dirs should be
  174. returned. By default, the first item from ``XDG_CONFIG_DIRS`` is
  175. returned, or :samp:`/etc/xdg/{AppName}`, if ``XDG_CONFIG_DIRS`` is not set
  176. Typical user data directories are:
  177. Mac OS X
  178. same as site_data_dir
  179. Unix
  180. ``/etc/xdg/<AppName>`` or ``$XDG_CONFIG_DIRS[i]/<AppName>`` for each
  181. value in ``$XDG_CONFIG_DIRS``
  182. Win *
  183. same as site_data_dir
  184. Vista
  185. Fail! "C:\ProgramData" is a hidden *system* directory on Vista.
  186. For Unix, this is using the ``$XDG_CONFIG_DIRS[0]`` default, if ``multipath=False``
  187. WARNING: Do not use this on Windows. See the Vista-Fail note above for why.
  188. """
  189. if sys.platform in [ "win32", "darwin" ]:
  190. path = site_data_dir(appname, appauthor)
  191. if appname and version:
  192. path = os.path.join(path, version)
  193. else:
  194. # XDG default for $XDG_CONFIG_DIRS
  195. # only first, if multipath is False
  196. path = os.getenv('XDG_CONFIG_DIRS', '/etc/xdg')
  197. pathlist = [ os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep) ]
  198. if appname:
  199. if version:
  200. appname = os.path.join(appname, version)
  201. pathlist = [ os.sep.join([x, appname]) for x in pathlist ]
  202. if multipath:
  203. path = os.pathsep.join(pathlist)
  204. else:
  205. path = pathlist[0]
  206. return path
  207. def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True):
  208. r"""Return full path to the user-specific cache dir for this application.
  209. "appname" is the name of application.
  210. If None, just the system directory is returned.
  211. "appauthor" (only required and used on Windows) is the name of the
  212. appauthor or distributing body for this application. Typically
  213. it is the owning company name. This falls back to appname.
  214. "version" is an optional version path element to append to the
  215. path. You might want to use this if you want multiple versions
  216. of your app to be able to run independently. If used, this
  217. would typically be "<major>.<minor>".
  218. Only applied when appname is present.
  219. "opinion" (boolean) can be False to disable the appending of
  220. "Cache" to the base app data dir for Windows. See
  221. discussion below.
  222. Typical user cache directories are:
  223. Mac OS X
  224. ~/Library/Caches/<AppName>
  225. Unix
  226. ~/.cache/<AppName> (XDG default)
  227. Win XP
  228. C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Cache
  229. Vista
  230. C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Cache
  231. On Windows the only suggestion in the MSDN docs is that local settings go in
  232. the ``CSIDL_LOCAL_APPDATA`` directory. This is identical to the non-roaming
  233. app data dir (the default returned by ``user_data_dir`` above). Apps typically
  234. put cache data somewhere *under* the given dir here. Some examples:
  235. - ...\Mozilla\Firefox\Profiles\<ProfileName>\Cache
  236. - ...\Acme\SuperApp\Cache\1.0
  237. OPINION: This function appends "Cache" to the ``CSIDL_LOCAL_APPDATA`` value.
  238. This can be disabled with the ``opinion=False`` option.
  239. """
  240. if sys.platform == "win32":
  241. if appauthor is None:
  242. appauthor = appname
  243. path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA"))
  244. if appname:
  245. path = os.path.join(path, appauthor, appname)
  246. if opinion:
  247. path = os.path.join(path, "Cache")
  248. elif sys.platform == 'darwin':
  249. path = os.path.expanduser('~/Library/Caches')
  250. if appname:
  251. path = os.path.join(path, appname)
  252. else:
  253. path = os.getenv('XDG_CACHE_HOME', os.path.expanduser('~/.cache'))
  254. if appname:
  255. path = os.path.join(path, appname)
  256. if appname and version:
  257. path = os.path.join(path, version)
  258. return path
  259. def user_log_dir(appname=None, appauthor=None, version=None, opinion=True):
  260. r"""Return full path to the user-specific log dir for this application.
  261. "appname" is the name of application.
  262. If None, just the system directory is returned.
  263. "appauthor" (only required and used on Windows) is the name of the
  264. appauthor or distributing body for this application. Typically
  265. it is the owning company name. This falls back to appname.
  266. "version" is an optional version path element to append to the
  267. path. You might want to use this if you want multiple versions
  268. of your app to be able to run independently. If used, this
  269. would typically be "<major>.<minor>".
  270. Only applied when appname is present.
  271. "opinion" (boolean) can be False to disable the appending of
  272. "Logs" to the base app data dir for Windows, and "log" to the
  273. base cache dir for Unix. See discussion below.
  274. Typical user cache directories are:
  275. Mac OS X: ~/Library/Logs/<AppName>
  276. Unix: ~/.cache/<AppName>/log # or under $XDG_CACHE_HOME if defined
  277. Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Logs
  278. Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Logs
  279. On Windows the only suggestion in the MSDN docs is that local settings
  280. go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in
  281. examples of what some windows apps use for a logs dir.)
  282. OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA`
  283. value for Windows and appends "log" to the user cache dir for Unix.
  284. This can be disabled with the `opinion=False` option.
  285. """
  286. if sys.platform == "darwin":
  287. path = os.path.join(
  288. os.path.expanduser('~/Library/Logs'),
  289. appname)
  290. elif sys.platform == "win32":
  291. path = user_data_dir(appname, appauthor, version); version=False
  292. if opinion:
  293. path = os.path.join(path, "Logs")
  294. else:
  295. path = user_cache_dir(appname, appauthor, version); version=False
  296. if opinion:
  297. path = os.path.join(path, "log")
  298. if appname and version:
  299. path = os.path.join(path, version)
  300. return path
  301. class AppDirs(object):
  302. """Convenience wrapper for getting application dirs."""
  303. def __init__(self, appname, appauthor=None, version=None,
  304. roaming=False, multipath=False):
  305. self.appname = appname
  306. self.appauthor = appauthor
  307. self.version = version
  308. self.roaming = roaming
  309. self.multipath = multipath
  310. @property
  311. def user_data_dir(self):
  312. return user_data_dir(self.appname, self.appauthor,
  313. version=self.version, roaming=self.roaming)
  314. @property
  315. def site_data_dir(self):
  316. return site_data_dir(self.appname, self.appauthor,
  317. version=self.version, multipath=self.multipath)
  318. @property
  319. def user_config_dir(self):
  320. return user_config_dir(self.appname, self.appauthor,
  321. version=self.version, roaming=self.roaming)
  322. @property
  323. def site_config_dir(self):
  324. return site_data_dir(self.appname, self.appauthor,
  325. version=self.version, multipath=self.multipath)
  326. @property
  327. def user_cache_dir(self):
  328. return user_cache_dir(self.appname, self.appauthor,
  329. version=self.version)
  330. @property
  331. def user_log_dir(self):
  332. return user_log_dir(self.appname, self.appauthor,
  333. version=self.version)
  334. #---- internal support stuff
  335. def _get_win_folder_from_registry(csidl_name):
  336. """This is a fallback technique at best. I'm not sure if using the
  337. registry for this guarantees us the correct answer for all CSIDL_*
  338. names.
  339. """
  340. import winreg as _winreg
  341. shell_folder_name = {
  342. "CSIDL_APPDATA": "AppData",
  343. "CSIDL_COMMON_APPDATA": "Common AppData",
  344. "CSIDL_LOCAL_APPDATA": "Local AppData",
  345. }[csidl_name]
  346. key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
  347. r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
  348. dir, type = _winreg.QueryValueEx(key, shell_folder_name)
  349. return dir
  350. def _get_win_folder_with_pywin32(csidl_name):
  351. from win32com.shell import shellcon, shell
  352. dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0)
  353. # Try to make this a unicode path because SHGetFolderPath does
  354. # not return unicode strings when there is unicode data in the
  355. # path.
  356. try:
  357. dir = str(dir)
  358. # Downgrade to short path name if have highbit chars. See
  359. # <http://bugs.activestate.com/show_bug.cgi?id=85099>.
  360. has_high_char = False
  361. for c in dir:
  362. if ord(c) > 255:
  363. has_high_char = True
  364. break
  365. if has_high_char:
  366. try:
  367. import win32api
  368. dir = win32api.GetShortPathName(dir)
  369. except ImportError:
  370. pass
  371. except UnicodeError:
  372. pass
  373. return dir
  374. def _get_win_folder_with_ctypes(csidl_name):
  375. import ctypes
  376. csidl_const = {
  377. "CSIDL_APPDATA": 26,
  378. "CSIDL_COMMON_APPDATA": 35,
  379. "CSIDL_LOCAL_APPDATA": 28,
  380. }[csidl_name]
  381. buf = ctypes.create_unicode_buffer(1024)
  382. ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)
  383. # Downgrade to short path name if have highbit chars. See
  384. # <http://bugs.activestate.com/show_bug.cgi?id=85099>.
  385. has_high_char = False
  386. for c in buf:
  387. if ord(c) > 255:
  388. has_high_char = True
  389. break
  390. if has_high_char:
  391. buf2 = ctypes.create_unicode_buffer(1024)
  392. if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):
  393. buf = buf2
  394. return buf.value
  395. if sys.platform == "win32":
  396. try:
  397. import win32com.shell
  398. _get_win_folder = _get_win_folder_with_pywin32
  399. except ImportError:
  400. try:
  401. import ctypes
  402. _get_win_folder = _get_win_folder_with_ctypes
  403. except ImportError:
  404. _get_win_folder = _get_win_folder_from_registry
  405. #---- self test code
  406. if __name__ == "__main__":
  407. appname = "MyApp"
  408. appauthor = "MyCompany"
  409. props = ("user_data_dir", "site_data_dir",
  410. "user_config_dir", "site_config_dir",
  411. "user_cache_dir", "user_log_dir")
  412. print("-- app dirs (with optional 'version')")
  413. dirs = AppDirs(appname, appauthor, version="1.0")
  414. for prop in props:
  415. print("%s: %s" % (prop, getattr(dirs, prop)))
  416. print("\n-- app dirs (without optional 'version')")
  417. dirs = AppDirs(appname, appauthor)
  418. for prop in props:
  419. print("%s: %s" % (prop, getattr(dirs, prop)))
  420. print("\n-- app dirs (without optional 'appauthor')")
  421. dirs = AppDirs(appname)
  422. for prop in props:
  423. print("%s: %s" % (prop, getattr(dirs, prop)))
上海开阖软件有限公司 沪ICP备12045867号-1