首页 > 解决方案 > Resolving symlinks in Python without failing with missing components (like "readlink -m")

问题描述

GNU readlink supports a command-line invocation similar to:

readlink -m /some/path/which/may/contain/symlinks

...which takes a path as an argument, and returns a path that does not contain any symlinks as a result (insofar as it is possible to do this), by replacing those link elements with the "real"/absolute paths they refer to. Unlike readlink -f or readlink -e, this tolerates (proceeds without failure) when any path element does not exist.

Is any equivalent operation available in Python?

标签: python

解决方案


os.path.realpath()做这个。

$ rm -rf -- /tmp/nonexisting.XYZ     # just to be extra clear
$ orig_path=/tmp/nonexisting.XYZ/foo # on MacOS, where /tmp is at /private/tmp
$ greadlink -m "$orig_path"          # demonstrate GNU readlink output for comparison...
/private/tmp/nonexisting.XYZ/foo
$ python -c 'import os.path, sys; print(os.path.realpath(sys.argv[1]))' "$orig_path"
/private/tmp/nonexisting.XYZ/foo

推荐阅读