擅长:python、mysql、java
<p><code>os.readlink()</code>的问题是它只能解决链接的一个步骤。我们可能会遇到这样的情况,即<code>A</code>链接到另一个链接<code>B</code>,而<code>B</code>链接处于悬挂状态。</p>
<pre><code>$ 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
</code></pre>
<p>现在在Python中,<code>os.readlink</code>为您提供了第一个目标。</p>
<pre><code>>>> import os
>>> os.readlink('A')
'/tmp/example/B'
</code></pre>
<p>但在大多数情况下,我认为我们对解决路径感兴趣。因此<code>pathlib</code>可以在这里提供帮助:</p>
<pre><code>>>> from pathlib import Path
>>> Path('A').resolve()
PosixPath('/tmp/example/notexist')
</code></pre>
<p>对于较旧的Python版本:</p>
<pre><code>>>> os.path.realpath('A')
'/tmp/example/notexist'
</code></pre>