Python 3 不通过统计检测符号链接

Python 3 does not detect symlinks via stat

我 运行 遇到了一个奇怪的情况,似乎不同的 Python 模块(osstatpathlib)识别不同,如果一个文件是否为symlink。

让我们以 python3 二进制文件为例:

paris@pk-tools:~$ ls -la /usr/bin/python3
lrwxrwxrwx 1 root root 9 Mar 23  2016 /usr/bin/python3 -> python3.5

如您所见,根据上面的shell命令,它是一个符号link。

如果我使用 Python 3.4 中引入的 pathlib 模块,这被识别为符号 link 成功:

>>> from pathlib import Path
>>> Path('/usr/bin/python3').is_symlink()
True

现在,如果我使用 os and stat Python 模块而不是 pathlib,则文件不会被识别为符号 link:

>>> import os
>>> import stat
>>> st_mode = os.stat('/usr/bin/python3').st_mode
>>> st_mode
33261
>>> stat.S_ISLNK(st_mode)
False

我最初通过 Docker 在 Docker 容器中为 Mac 尝试了此操作,然后在普通 Ubuntu 16.04 中尝试了此操作,结果相同。

知道为什么会这样吗?

谢谢!

os.stat 解析其目标。当您需要有关符号链接本身的信息时,请使用 os.lstat

这是the documentation

os.stat(path)

Perform the equivalent of a stat() system call on the given path. (This function follows symlinks; to stat a symlink use lstat().)

os.lstat(path)

Perform the equivalent of an lstat() system call on the given path. Similar to stat(), but does not follow symbolic links. On platforms that do not support symbolic links, this is an alias for stat().