Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 305
Dmitry Petrov Avatar asked Oct 21 '25 14:10

Dmitry Petrov


1 Answers

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.

like image 53
Étienne Avatar answered Oct 23 '25 04:10

Étienne