Dmitry Petrov
Dmitry Petrov

Reputation: 1547

Python os.path.realpath() for symlink in Windows

It seems like realpath() does not resolve symlink (not shortcut - *.lnk) in Windows. I found an open bug for python3 here: https://bugs.python.org/issue9949

Is there any workaround? I'm mostly interested in Python 2.

Upvotes: 4

Views: 5698

Answers (2)

Jason R. Coombs
Jason R. Coombs

Reputation: 42724

The jaraco.windows project supplies jaraco.windows.filesystem.get_final_path which may be what you're looking for. With the 3.9 release, it also has a jaraco.windows.filesystem.backports module, which presents the realpath function as proposed for that Python bug. Please give one or both of those functions a try and report back how it works.

If the realpath function works well for you, there is a patch_os_module, which as its name suggests, can patch the os module such that os.path.realpath has the behavior from the backport. At the time of this writing, it doesn't do that, but if that would be useful for your use-case, I'd be happy to add it.

Feel free to contribute to the project in Github. And please excuse the docs - they don't build properly on a Unix system such as RTD.

Upvotes: 1

Étienne
Étienne

Reputation: 451

The Python function os.path.realpath() returns the canonical path of the given path, eliminating simlinks.

On Windows 7, this function does not work as expected as it fails to follow symbolic links (created with mklink. Since the bug has been opened for more than 7 years, I started looking for a workaround.

The solution I found was to replace

realpath = os.path.realpath(path)

by

realpath = path if not os.path.islink(path) else os.readlink(path)

Function os.readlink() does work correctly on Windows 7.

Upvotes: 4

Related Questions