| 1 |
"""Common operations on Posix pathnames. |
| 2 |
|
| 3 |
Instead of importing this module directly, import os and refer to |
| 4 |
this module as os.path. The "os.path" name is an alias for this |
| 5 |
module on Posix systems; on other systems (e.g. Windows), |
| 6 |
os.path provides the same operations in a manner specific to that |
| 7 |
platform, and is an alias to another module (e.g. ntpath). |
| 8 |
|
| 9 |
Some of this can actually be useful on non-Posix systems too, e.g. |
| 10 |
for manipulation of the pathname component of URLs. |
| 11 |
""" |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
curdir = '.' |
| 17 |
pardir = '..' |
| 18 |
extsep = '.' |
| 19 |
sep = '/' |
| 20 |
pathsep = ':' |
| 21 |
defpath = '/bin:/usr/bin' |
| 22 |
altsep = None |
| 23 |
devnull = '/dev/null' |
| 24 |
|
| 25 |
import os |
| 26 |
import sys |
| 27 |
import stat |
| 28 |
import genericpath |
| 29 |
from genericpath import * |
| 30 |
|
| 31 |
__all__ = ["normcase","isabs","join","splitdrive","split","splitext", |
| 32 |
"basename","dirname","commonprefix","getsize","getmtime", |
| 33 |
"getatime","getctime","islink","exists","lexists","isdir","isfile", |
| 34 |
"ismount", "expanduser","expandvars","normpath","abspath", |
| 35 |
"samefile","sameopenfile","samestat", |
| 36 |
"curdir","pardir","sep","pathsep","defpath","altsep","extsep", |
| 37 |
"devnull","realpath","supports_unicode_filenames","relpath", |
| 38 |
"commonpath", "ALLOW_MISSING"] |
| 39 |
|
| 40 |
|
| 41 |
def _get_sep(path): |
| 42 |
if isinstance(path, bytes): |
| 43 |
return b'/' |
| 44 |
else: |
| 45 |
return '/' |
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
def normcase(s): |
| 53 |
"""Normalize case of pathname. Has no effect under Posix""" |
| 54 |
return os.fspath(s) |
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
def isabs(s): |
| 61 |
"""Test whether a path is absolute""" |
| 62 |
s = os.fspath(s) |
| 63 |
sep = _get_sep(s) |
| 64 |
return s.startswith(sep) |
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
def join(a, *p): |
| 72 |
"""Join two or more pathname components, inserting '/' as needed. |
| 73 |
If any component is an absolute path, all previous path components |
| 74 |
will be discarded. An empty last part will result in a path that |
| 75 |
ends with a separator.""" |
| 76 |
a = os.fspath(a) |
| 77 |
sep = _get_sep(a) |
| 78 |
path = a |
| 79 |
try: |
| 80 |
if not p: |
| 81 |
path[:0] + sep |
| 82 |
for b in map(os.fspath, p): |
| 83 |
if b.startswith(sep): |
| 84 |
path = b |
| 85 |
elif not path or path.endswith(sep): |
| 86 |
path += b |
| 87 |
else: |
| 88 |
path += sep + b |
| 89 |
except (TypeError, AttributeError, BytesWarning): |
| 90 |
genericpath._check_arg_types('join', a, *p) |
| 91 |
raise |
| 92 |
return path |
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
def split(p): |
| 101 |
"""Split a pathname. Returns tuple "(head, tail)" where "tail" is |
| 102 |
everything after the final slash. Either part may be empty.""" |
| 103 |
p = os.fspath(p) |
| 104 |
sep = _get_sep(p) |
| 105 |
i = p.rfind(sep) + 1 |
| 106 |
head, tail = p[:i], p[i:] |
| 107 |
if head and head != sep*len(head): |
| 108 |
head = head.rstrip(sep) |
| 109 |
return head, tail |
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
def splitext(p): |
| 118 |
p = os.fspath(p) |
| 119 |
if isinstance(p, bytes): |
| 120 |
sep = b'/' |
| 121 |
extsep = b'.' |
| 122 |
else: |
| 123 |
sep = '/' |
| 124 |
extsep = '.' |
| 125 |
return genericpath._splitext(p, sep, None, extsep) |
| 126 |
splitext.__doc__ = genericpath._splitext.__doc__ |
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
def splitdrive(p): |
| 132 |
"""Split a pathname into drive and path. On Posix, drive is always |
| 133 |
empty.""" |
| 134 |
p = os.fspath(p) |
| 135 |
return p[:0], p |
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
def basename(p): |
| 141 |
"""Returns the final component of a pathname""" |
| 142 |
p = os.fspath(p) |
| 143 |
sep = _get_sep(p) |
| 144 |
i = p.rfind(sep) + 1 |
| 145 |
return p[i:] |
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
def dirname(p): |
| 151 |
"""Returns the directory component of a pathname""" |
| 152 |
p = os.fspath(p) |
| 153 |
sep = _get_sep(p) |
| 154 |
i = p.rfind(sep) + 1 |
| 155 |
head = p[:i] |
| 156 |
if head and head != sep*len(head): |
| 157 |
head = head.rstrip(sep) |
| 158 |
return head |
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
def islink(path): |
| 165 |
"""Test whether a path is a symbolic link""" |
| 166 |
try: |
| 167 |
st = os.lstat(path) |
| 168 |
except (OSError, ValueError, AttributeError): |
| 169 |
return False |
| 170 |
return stat.S_ISLNK(st.st_mode) |
| 171 |
|
| 172 |
|
| 173 |
|
| 174 |
def lexists(path): |
| 175 |
"""Test whether a path exists. Returns True for broken symbolic links""" |
| 176 |
try: |
| 177 |
os.lstat(path) |
| 178 |
except (OSError, ValueError): |
| 179 |
return False |
| 180 |
return True |
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
|
| 186 |
def ismount(path): |
| 187 |
"""Test whether a path is a mount point""" |
| 188 |
try: |
| 189 |
s1 = os.lstat(path) |
| 190 |
except (OSError, ValueError): |
| 191 |
|
| 192 |
return False |
| 193 |
else: |
| 194 |
|
| 195 |
if stat.S_ISLNK(s1.st_mode): |
| 196 |
return False |
| 197 |
|
| 198 |
path = os.fspath(path) |
| 199 |
if isinstance(path, bytes): |
| 200 |
parent = join(path, b'..') |
| 201 |
else: |
| 202 |
parent = join(path, '..') |
| 203 |
parent = realpath(parent) |
| 204 |
try: |
| 205 |
s2 = os.lstat(parent) |
| 206 |
except (OSError, ValueError): |
| 207 |
return False |
| 208 |
|
| 209 |
dev1 = s1.st_dev |
| 210 |
dev2 = s2.st_dev |
| 211 |
if dev1 != dev2: |
| 212 |
return True |
| 213 |
ino1 = s1.st_ino |
| 214 |
ino2 = s2.st_ino |
| 215 |
if ino1 == ino2: |
| 216 |
return True |
| 217 |
return False |
| 218 |
|
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 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 |
|
| 249 |
return path |
| 250 |
try: |
| 251 |
userhome = pwd.getpwuid(os.getuid()).pw_dir |
| 252 |
except KeyError: |
| 253 |
|
| 254 |
|
| 255 |
return path |
| 256 |
else: |
| 257 |
userhome = os.environ['HOME'] |
| 258 |
else: |
| 259 |
try: |
| 260 |
import pwd |
| 261 |
except ImportError: |
| 262 |
|
| 263 |
return path |
| 264 |
name = path[1:i] |
| 265 |
if isinstance(name, bytes): |
| 266 |
name = str(name, 'ASCII') |
| 267 |
try: |
| 268 |
pwent = pwd.getpwnam(name) |
| 269 |
except KeyError: |
| 270 |
|
| 271 |
|
| 272 |
return path |
| 273 |
userhome = pwent.pw_dir |
| 274 |
|
| 275 |
if userhome is None and sys.platform == "vxworks": |
| 276 |
return path |
| 277 |
if isinstance(path, bytes): |
| 278 |
userhome = os.fsencode(userhome) |
| 279 |
root = b'/' |
| 280 |
else: |
| 281 |
root = '/' |
| 282 |
userhome = userhome.rstrip(root) |
| 283 |
return (userhome + path[i:]) or root |
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
|
| 289 |
|
| 290 |
_varpattern = r'\$(\w+|\{[^}]*\}?)' |
| 291 |
_varsub = None |
| 292 |
_varsubb = None |
| 293 |
|
| 294 |
def expandvars(path): |
| 295 |
"""Expand shell variables of form $var and ${var}. Unknown variables |
| 296 |
are left unchanged.""" |
| 297 |
path = os.fspath(path) |
| 298 |
global _varsub, _varsubb |
| 299 |
if isinstance(path, bytes): |
| 300 |
if b'$' not in path: |
| 301 |
return path |
| 302 |
if not _varsubb: |
| 303 |
import re |
| 304 |
_varsubb = re.compile(_varpattern.encode(), re.ASCII).sub |
| 305 |
sub = _varsubb |
| 306 |
start = b'{' |
| 307 |
end = b'}' |
| 308 |
environ = getattr(os, 'environb', None) |
| 309 |
else: |
| 310 |
if '$' not in path: |
| 311 |
return path |
| 312 |
if not _varsub: |
| 313 |
import re |
| 314 |
_varsub = re.compile(_varpattern, re.ASCII).sub |
| 315 |
sub = _varsub |
| 316 |
start = '{' |
| 317 |
end = '}' |
| 318 |
environ = os.environ |
| 319 |
|
| 320 |
def repl(m): |
| 321 |
name = m[1] |
| 322 |
if name.startswith(start): |
| 323 |
if not name.endswith(end): |
| 324 |
return m[0] |
| 325 |
name = name[1:-1] |
| 326 |
try: |
| 327 |
if environ is None: |
| 328 |
value = os.fsencode(os.environ[os.fsdecode(name)]) |
| 329 |
else: |
| 330 |
value = environ[name] |
| 331 |
except KeyError: |
| 332 |
return m[0] |
| 333 |
else: |
| 334 |
return value |
| 335 |
|
| 336 |
return sub(repl, path) |
| 337 |
|
| 338 |
|
| 339 |
|
| 340 |
|
| 341 |
|
| 342 |
|
| 343 |
try: |
| 344 |
from posix import _path_normpath |
| 345 |
|
| 346 |
except ImportError: |
| 347 |
def normpath(path): |
| 348 |
"""Normalize path, eliminating double slashes, etc.""" |
| 349 |
path = os.fspath(path) |
| 350 |
if isinstance(path, bytes): |
| 351 |
sep = b'/' |
| 352 |
empty = b'' |
| 353 |
dot = b'.' |
| 354 |
dotdot = b'..' |
| 355 |
else: |
| 356 |
sep = '/' |
| 357 |
empty = '' |
| 358 |
dot = '.' |
| 359 |
dotdot = '..' |
| 360 |
if path == empty: |
| 361 |
return dot |
| 362 |
initial_slashes = path.startswith(sep) |
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
if (initial_slashes and |
| 367 |
path.startswith(sep*2) and not path.startswith(sep*3)): |
| 368 |
initial_slashes = 2 |
| 369 |
comps = path.split(sep) |
| 370 |
new_comps = [] |
| 371 |
for comp in comps: |
| 372 |
if comp in (empty, dot): |
| 373 |
continue |
| 374 |
if (comp != dotdot or (not initial_slashes and not new_comps) or |
| 375 |
(new_comps and new_comps[-1] == dotdot)): |
| 376 |
new_comps.append(comp) |
| 377 |
elif new_comps: |
| 378 |
new_comps.pop() |
| 379 |
comps = new_comps |
| 380 |
path = sep.join(comps) |
| 381 |
if initial_slashes: |
| 382 |
path = sep*initial_slashes + path |
| 383 |
return path or dot |
| 384 |
|
| 385 |
else: |
| 386 |
def normpath(path): |
| 387 |
"""Normalize path, eliminating double slashes, etc.""" |
| 388 |
path = os.fspath(path) |
| 389 |
if isinstance(path, bytes): |
| 390 |
return os.fsencode(_path_normpath(os.fsdecode(path))) or b"." |
| 391 |
return _path_normpath(path) or "." |
| 392 |
|
| 393 |
|
| 394 |
def abspath(path): |
| 395 |
"""Return an absolute path.""" |
| 396 |
path = os.fspath(path) |
| 397 |
if not isabs(path): |
| 398 |
if isinstance(path, bytes): |
| 399 |
cwd = os.getcwdb() |
| 400 |
else: |
| 401 |
cwd = os.getcwd() |
| 402 |
path = join(cwd, path) |
| 403 |
return normpath(path) |
| 404 |
|
| 405 |
|
| 406 |
|
| 407 |
|
| 408 |
|
| 409 |
def realpath(filename, *, strict=False): |
| 410 |
"""Return the canonical path of the specified filename, eliminating any |
| 411 |
symbolic links encountered in the path.""" |
| 412 |
filename = os.fspath(filename) |
| 413 |
path, ok = _joinrealpath(filename[:0], filename, strict, {}) |
| 414 |
return abspath(path) |
| 415 |
|
| 416 |
|
| 417 |
|
| 418 |
def _joinrealpath(path, rest, strict, seen): |
| 419 |
if isinstance(path, bytes): |
| 420 |
sep = b'/' |
| 421 |
curdir = b'.' |
| 422 |
pardir = b'..' |
| 423 |
else: |
| 424 |
sep = '/' |
| 425 |
curdir = '.' |
| 426 |
pardir = '..' |
| 427 |
getcwd = os.getcwd |
| 428 |
if strict is ALLOW_MISSING: |
| 429 |
ignored_error = FileNotFoundError |
| 430 |
elif strict: |
| 431 |
ignored_error = () |
| 432 |
else: |
| 433 |
ignored_error = OSError |
| 434 |
|
| 435 |
maxlinks = None |
| 436 |
|
| 437 |
if isabs(rest): |
| 438 |
rest = rest[1:] |
| 439 |
path = sep |
| 440 |
|
| 441 |
while rest: |
| 442 |
name, _, rest = rest.partition(sep) |
| 443 |
if not name or name == curdir: |
| 444 |
|
| 445 |
continue |
| 446 |
if name == pardir: |
| 447 |
|
| 448 |
if path: |
| 449 |
path, name = split(path) |
| 450 |
if name == pardir: |
| 451 |
path = join(path, pardir, pardir) |
| 452 |
else: |
| 453 |
path = pardir |
| 454 |
continue |
| 455 |
newpath = join(path, name) |
| 456 |
try: |
| 457 |
st = os.lstat(newpath) |
| 458 |
except ignored_error: |
| 459 |
is_link = False |
| 460 |
else: |
| 461 |
is_link = stat.S_ISLNK(st.st_mode) |
| 462 |
if not is_link: |
| 463 |
path = newpath |
| 464 |
continue |
| 465 |
|
| 466 |
if newpath in seen: |
| 467 |
|
| 468 |
path = seen[newpath] |
| 469 |
if path is not None: |
| 470 |
|
| 471 |
continue |
| 472 |
|
| 473 |
if strict: |
| 474 |
|
| 475 |
os.stat(newpath) |
| 476 |
else: |
| 477 |
|
| 478 |
return join(newpath, rest), False |
| 479 |
seen[newpath] = None |
| 480 |
path, ok = _joinrealpath(path, os.readlink(newpath), strict, seen) |
| 481 |
if not ok: |
| 482 |
return join(path, rest), False |
| 483 |
seen[newpath] = path |
| 484 |
|
| 485 |
return path, True |
| 486 |
|
| 487 |
|
| 488 |
supports_unicode_filenames = (sys.platform == 'darwin') |
| 489 |
|
| 490 |
def relpath(path, start=None): |
| 491 |
"""Return a relative version of a path""" |
| 492 |
|
| 493 |
if not path: |
| 494 |
raise ValueError("no path specified") |
| 495 |
|
| 496 |
path = os.fspath(path) |
| 497 |
if isinstance(path, bytes): |
| 498 |
curdir = b'.' |
| 499 |
sep = b'/' |
| 500 |
pardir = b'..' |
| 501 |
else: |
| 502 |
curdir = '.' |
| 503 |
sep = '/' |
| 504 |
pardir = '..' |
| 505 |
|
| 506 |
if start is None: |
| 507 |
start = curdir |
| 508 |
else: |
| 509 |
start = os.fspath(start) |
| 510 |
|
| 511 |
try: |
| 512 |
start_list = [x for x in abspath(start).split(sep) if x] |
| 513 |
path_list = [x for x in abspath(path).split(sep) if x] |
| 514 |
|
| 515 |
i = len(commonprefix([start_list, path_list])) |
| 516 |
|
| 517 |
rel_list = [pardir] * (len(start_list)-i) + path_list[i:] |
| 518 |
if not rel_list: |
| 519 |
return curdir |
| 520 |
return join(*rel_list) |
| 521 |
except (TypeError, AttributeError, BytesWarning, DeprecationWarning): |
| 522 |
genericpath._check_arg_types('relpath', path, start) |
| 523 |
raise |
| 524 |
|
| 525 |
|
| 526 |
|
| 527 |
|
| 528 |
|
| 529 |
|
| 530 |
|
| 531 |
def commonpath(paths): |
| 532 |
"""Given a sequence of path names, returns the longest common sub-path.""" |
| 533 |
|
| 534 |
if not paths: |
| 535 |
raise ValueError('commonpath() arg is an empty sequence') |
| 536 |
|
| 537 |
paths = tuple(map(os.fspath, paths)) |
| 538 |
if isinstance(paths[0], bytes): |
| 539 |
sep = b'/' |
| 540 |
curdir = b'.' |
| 541 |
else: |
| 542 |
sep = '/' |
| 543 |
curdir = '.' |
| 544 |
|
| 545 |
try: |
| 546 |
split_paths = [path.split(sep) for path in paths] |
| 547 |
|
| 548 |
try: |
| 549 |
isabs, = set(p[:1] == sep for p in paths) |
| 550 |
except ValueError: |
| 551 |
raise ValueError("Can't mix absolute and relative paths") from None |
| 552 |
|
| 553 |
split_paths = [[c for c in s if c and c != curdir] for s in split_paths] |
| 554 |
s1 = min(split_paths) |
| 555 |
s2 = max(split_paths) |
| 556 |
common = s1 |
| 557 |
for i, c in enumerate(s1): |
| 558 |
if c != s2[i]: |
| 559 |
common = s1[:i] |
| 560 |
break |
| 561 |
|
| 562 |
prefix = sep if isabs else sep[:0] |
| 563 |
return prefix + sep.join(common) |
| 564 |
except (TypeError, AttributeError): |
| 565 |
genericpath._check_arg_types('commonpath', *paths) |
| 566 |
raise |