Skip to main content

Canonicalizes a path and follows any symlinks.

#!/usr/bin/env python3

"""
Canonicalizes a path and follows any symlinks.

This is the equivalent of `readlink -f` on many Linux systems. This is
useful as there are often differences in readlink on different
platforms.

Original: https://github.com/certbot/certbot/blob/master/tools/readlink.py
"""

import os
import sys


def main(link):
    realpath = os.path.realpath(link)
    if not os.path.exists(realpath):
        sys.stderr.write("Error : '{0}' does not exist\n".format(realpath))
        sys.exit(1)
    return realpath


if __name__ == '__main__':
    if len(sys.argv) < 2:
        sys.stderr.write("Error : missing path argument\n")
        sys.exit(1)
    print(main(sys.argv[1]))