Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path.
(filename, *, strict=False)
| 386 | # filesystem). |
| 387 | |
| 388 | def realpath(filename, *, strict=False): |
| 389 | """Return the canonical path of the specified filename, eliminating any |
| 390 | symbolic links encountered in the path.""" |
| 391 | filename = os.fspath(filename) |
| 392 | if isinstance(filename, bytes): |
| 393 | sep = b'/' |
| 394 | curdir = b'.' |
| 395 | pardir = b'..' |
| 396 | getcwd = os.getcwdb |
| 397 | else: |
| 398 | sep = '/' |
| 399 | curdir = '.' |
| 400 | pardir = '..' |
| 401 | getcwd = os.getcwd |
| 402 | if strict is ALLOW_MISSING: |
| 403 | ignored_error = FileNotFoundError |
| 404 | strict = True |
| 405 | elif strict: |
| 406 | ignored_error = () |
| 407 | else: |
| 408 | ignored_error = OSError |
| 409 | |
| 410 | lstat = os.lstat |
| 411 | readlink = os.readlink |
| 412 | maxlinks = None |
| 413 | |
| 414 | # The stack of unresolved path parts. When popped, a special value of None |
| 415 | # indicates that a symlink target has been resolved, and that the original |
| 416 | # symlink path can be retrieved by popping again. The [::-1] slice is a |
| 417 | # very fast way of spelling list(reversed(...)). |
| 418 | rest = filename.split(sep)[::-1] |
| 419 | |
| 420 | # Number of unprocessed parts in 'rest'. This can differ from len(rest) |
| 421 | # later, because 'rest' might contain markers for unresolved symlinks. |
| 422 | part_count = len(rest) |
| 423 | |
| 424 | # The resolved path, which is absolute throughout this function. |
| 425 | # Note: getcwd() returns a normalized and symlink-free path. |
| 426 | path = sep if filename.startswith(sep) else getcwd() |
| 427 | |
| 428 | # Mapping from symlink paths to *fully resolved* symlink targets. If a |
| 429 | # symlink is encountered but not yet resolved, the value is None. This is |
| 430 | # used both to detect symlink loops and to speed up repeated traversals of |
| 431 | # the same links. |
| 432 | seen = {} |
| 433 | |
| 434 | # Number of symlinks traversed. When the number of traversals is limited |
| 435 | # by *maxlinks*, this is used instead of *seen* to detect symlink loops. |
| 436 | link_count = 0 |
| 437 | |
| 438 | while part_count: |
| 439 | name = rest.pop() |
| 440 | if name is None: |
| 441 | # resolved symlink target |
| 442 | seen[rest.pop()] = path |
| 443 | continue |
| 444 | part_count -= 1 |
| 445 | if not name or name == curdir: |