Search code examples
pythonpathlib

Get pathlib Path with symlink


Let's say I open a python console inside /home/me/symlink/dir, which is actually a shortcut to /home/me/path/to/the/dir. In this console I execute the following code:

from pathlib import Path
path = Path.cwd()
print(path)  # "/home/me/path/to/the/dir"

So cwd() actually resolves the symlinks and get the absolute path automatically and I am searching how to avoid this behavior. If the path with symlink is provided at the Path object declaration, it seems to work as I would like:

from pathlib import Path
path = Path("/home/me/symlink/dir")
print(path)  # "/home/me/symlink/dir"

Is there a way to get the current working directory keeping the symlink other than providing the path at object instantiation ?


Solution

  • you'll need to use os.getcwd() . Path.cwd() internally uses os.getcwdb() which resolves symlinks, while os.getcwd() preserves them.

    from pathlib import Path
    import os
    
    path = Path(os.getcwd())
    print(path)
    

    If you need work with symlinks in general.

    path.is_symlink() - check if a path is a symlink

    path.resolve() - resolve symlinks to get the actual path

    path.readlink() - get the target of a symlink

    path = Path(os.getcwd())
    if path.is_symlink():
        real_path = path.resolve()  # "/home/me/path/to/the/dir"
        symlink_target = path.readlink()  # Gets the symlink target
    

    Edit 1:

    For your test case, The PWD environment variable often contains the path with preserved symlinks, as it's typically maintained by the shell.

    import os
    from pathlib import Path
    
    def get_symlinked_cwd():
        
        return Path(os.getenv("PWD", os.getcwd()))
    
    symlink_path = get_symlinked_cwd()
    print(symlink_path)