The problem with os.readlink()
is it will only resolve 1 step of the link. We can have a situation where A
links to another link B
, and B
link is dangling.
$ ln -s /tmp/example/notexist /tmp/example/B
$ ln -s /tmp/example/B /tmp/example/A
$ ls -l /tmp/example
A -> /tmp/example/B
B -> /tmp/example/notexist
Now in Python, os.readlink
gives you the first target.
>>> import os
>>> os.readlink('A')
'/tmp/example/B'
But in most situations I assume we are interested in the resolved path. So pathlib
can help here:
>>> from pathlib import Path
>>> Path('A').resolve()
PosixPath('/tmp/example/notexist')
For older Python versions:
>>> os.path.realpath('A')
'/tmp/example/notexist'
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…