`readlink -m` equivalent function in Python to get canonical file name

Posted on In Programming, QA, Tutorial

readlink -m can get canonical file name by resolving every symlinks in every component of the given path recursively. In Python, the os.readlink() function does not do so. Any equivalent function in Python to the readlink -m command line?

Specifically, it does:

canonicalize by following every symlink in every component of the given name recursively, without requirements on components existence


`readlink -m` does 2 things:
– canonicalize by following every symlink in every component of the given name recursively, and
– without requirements on components existence

In Python, the equivalent function is `os.path.realpath()`.

One example is as follows. Note that the directory `/tmp/w` does not exist at all.

$ ls -lha
lrwxrwxrwx  1 ericma ericma    6 Nov 25 00:00 w -> /tmp/w
$ readlink -f ./w
/tmp/w
$ readlink -f ./w/x
$ readlink -m ./w/x
/tmp/w/x
$ python3
Python 3.6.8 (default, Oct  7 2019, 12:59:55) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.realpath("./w/x")
'/tmp/w/x'

Leave a Reply

Your email address will not be published. Required fields are marked *