Advertisement
cooperlees

pathlib relative path finding

Aug 3rd, 2020
2,363
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.08 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. from pathlib import Path
  4. from tempfile import TemporaryDirectory
  5.  
  6.  
  7. def relpath(path_to: Path, path_from: Path) -> Path:
  8.     path_to = Path(path_to).resolve()
  9.     path_from = Path(path_from).resolve()
  10.     try:
  11.         for p in (*reversed(path_from.parents), path_from):
  12.             head, tail = p, path_to.relative_to(p)
  13.     except ValueError:  # Stop when the paths diverge.
  14.         pass
  15.     return Path("../" * (len(path_from.parents) - len(head.parents))).joinpath(tail)
  16.  
  17.  
  18. a_package_name = "a_package"
  19.  
  20. with TemporaryDirectory() as td:
  21.     pypi_mirror_root = Path(td)
  22.     web_root = pypi_mirror_root / "web"
  23.     json_path = web_root / "json"
  24.     pkg_json_path = json_path / a_package_name
  25.     pkg_json_pypi_path = web_root / "pypi" / a_package_name / "json"
  26.  
  27.     json_path.mkdir(parents=True)
  28.     pkg_json_path.touch()
  29.     pkg_json_pypi_path.parent.mkdir(parents=True)
  30.  
  31.     rel_path = relpath(pkg_json_path, pkg_json_pypi_path)
  32.     pkg_json_pypi_path.symlink_to(rel_path)
  33.     print(f"Symlink made relative from {pkg_json_pypi_path} to {rel_path}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement