Expand ~ and ~user constructions. If user or $HOME is unknown, do nothing.
(path)
| 227 | # variable expansion.) |
| 228 | |
| 229 | def expanduser(path): |
| 230 | """Expand ~ and ~user constructions. If user or $HOME is unknown, |
| 231 | do nothing.""" |
| 232 | path = os.fspath(path) |
| 233 | if isinstance(path, bytes): |
| 234 | tilde = b'~' |
| 235 | else: |
| 236 | tilde = '~' |
| 237 | if not path.startswith(tilde): |
| 238 | return path |
| 239 | sep = _get_sep(path) |
| 240 | i = path.find(sep, 1) |
| 241 | if i < 0: |
| 242 | i = len(path) |
| 243 | if i == 1: |
| 244 | if 'HOME' not in os.environ: |
| 245 | try: |
| 246 | import pwd |
| 247 | except ImportError: |
| 248 | # pwd module unavailable, return path unchanged |
| 249 | return path |
| 250 | try: |
| 251 | userhome = pwd.getpwuid(os.getuid()).pw_dir |
| 252 | except KeyError: |
| 253 | # bpo-10496: if the current user identifier doesn't exist in the |
| 254 | # password database, return the path unchanged |
| 255 | return path |
| 256 | else: |
| 257 | userhome = os.environ['HOME'] |
| 258 | else: |
| 259 | try: |
| 260 | import pwd |
| 261 | except ImportError: |
| 262 | # pwd module unavailable, return path unchanged |
| 263 | return path |
| 264 | name = path[1:i] |
| 265 | if isinstance(name, bytes): |
| 266 | name = os.fsdecode(name) |
| 267 | try: |
| 268 | pwent = pwd.getpwnam(name) |
| 269 | except KeyError: |
| 270 | # bpo-10496: if the user name from the path doesn't exist in the |
| 271 | # password database, return the path unchanged |
| 272 | return path |
| 273 | userhome = pwent.pw_dir |
| 274 | # if no user home, return the path unchanged on VxWorks |
| 275 | if userhome is None and sys.platform == "vxworks": |
| 276 | return path |
| 277 | if isinstance(path, bytes): |
| 278 | userhome = os.fsencode(userhome) |
| 279 | userhome = userhome.rstrip(sep) |
| 280 | return (userhome + path[i:]) or sep |
| 281 | |
| 282 | |
| 283 | # Expand paths containing shell variable substitutions. |
nothing calls this directly
no test coverage detected