Return the 'home' directory, as a unicode string. Uses os.path.expanduser('~'), and checks for writability. See stdlib docs for how this is determined. For Python <3.8, $HOME is first priority on *ALL* platforms. For Python >=3.8 on Windows, %HOME% is no longer considered. Par
(require_writable=False)
| 168 | |
| 169 | |
| 170 | def get_home_dir(require_writable=False) -> str: |
| 171 | """Return the 'home' directory, as a unicode string. |
| 172 | |
| 173 | Uses os.path.expanduser('~'), and checks for writability. |
| 174 | |
| 175 | See stdlib docs for how this is determined. |
| 176 | For Python <3.8, $HOME is first priority on *ALL* platforms. |
| 177 | For Python >=3.8 on Windows, %HOME% is no longer considered. |
| 178 | |
| 179 | Parameters |
| 180 | ---------- |
| 181 | |
| 182 | require_writable : bool [default: False] |
| 183 | if True: |
| 184 | guarantees the return value is a writable directory, otherwise |
| 185 | raises HomeDirError |
| 186 | if False: |
| 187 | The path is resolved, but it is not guaranteed to exist or be writable. |
| 188 | """ |
| 189 | |
| 190 | homedir = os.path.expanduser('~') |
| 191 | # Next line will make things work even when /home/ is a symlink to |
| 192 | # /usr/home as it is on FreeBSD, for example |
| 193 | homedir = os.path.realpath(homedir) |
| 194 | |
| 195 | if not _writable_dir(homedir) and os.name == 'nt': |
| 196 | # expanduser failed, use the registry to get the 'My Documents' folder. |
| 197 | try: |
| 198 | import winreg as wreg |
| 199 | with wreg.OpenKey( |
| 200 | wreg.HKEY_CURRENT_USER, |
| 201 | r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" |
| 202 | ) as key: |
| 203 | homedir = wreg.QueryValueEx(key,'Personal')[0] |
| 204 | except: |
| 205 | pass |
| 206 | |
| 207 | if (not require_writable) or _writable_dir(homedir): |
| 208 | assert isinstance(homedir, str), "Homedir shoudl be unicode not bytes" |
| 209 | return homedir |
| 210 | else: |
| 211 | raise HomeDirError('%s is not a writable dir, ' |
| 212 | 'set $HOME environment variable to override' % homedir) |
| 213 | |
| 214 | def get_xdg_dir(): |
| 215 | """Return the XDG_CONFIG_HOME, if it is defined and exists, else None. |
no test coverage detected