Created
August 5, 2020 13:47
-
-
Save willprice/311faace6fb4f514376fa405d2220615 to your computer and use it in GitHub Desktop.
Create relative symlinks in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def relative_symlink(target: Union[Path, str], destination: Union[Path, str]): | |
"""Create a symlink pointing to ``target`` from ``location``. | |
Args: | |
target: The target of the symlink (the file/directory that is pointed to) | |
destination: The location of the symlink itself. | |
""" | |
target = Path(target) | |
destination = Path(destination) | |
target_dir = destination.parent | |
target_dir.mkdir(exist_ok=True, parents=True) | |
relative_source = os.path.relpath(target, target_dir) | |
dir_fd = os.open(str(target_dir.absolute()), os.O_RDONLY) | |
print(f"{relative_source} -> {destination.name} in {target_dir}") | |
try: | |
os.symlink(relative_source, destination.name, dir_fd=dir_fd) | |
finally: | |
os.close(dir_fd) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works like a charm. Thank you 🙂