Pathlib relative_to 远程共享边缘案例?

Pathlib relative_to remote share edge case?

似乎在 pathlib 中,远程共享路径(例如 //server/file.ext)没有为远程共享根目录中的文件计算合理的相对路径。

https://github.com/python/cpython/blob/3.10/Lib/pathlib.py#L789

有没有办法检查服务器路径是否相对于网络共享根目录中的文件可靠?

下面是 3 个示例,展示了我所期望的“正确”行为,后面是第 4 个似乎不正确的示例。

这是正确的/预期的:

>>> path_a = pathlib.Path('C:\bar\myfile.pdf')
>>> path_b = pathlib.Path('C:\bar')
>>> path_a.relative_to(path_b)
WindowsPath('myfile.pdf')

这是正确的/预期的:

>>> path_a = pathlib.Path('C:\myfile.pdf')
>>> path_b = pathlib.Path('C:\')
>>> path_a.relative_to(path_b)
WindowsPath('myfile.pdf')

这是正确的/预期的:

>>> path_a = pathlib.Path('//server01/bar/myfile.pdf')
>>> path_b = pathlib.Path('//server01/bar')
>>> path_a.relative_to(path_b)
WindowsPath('myfile.pdf')

这出乎意料:

>>> path_a = pathlib.Path('//server01/myfile.pdf')
>>> path_b = pathlib.Path('//server01')
>>> path_a.relative_to(path_b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\John\AppData\Local\Programs\Python\Python39\lib\pathlib.py", line 928, in relative_to
    raise ValueError("{!r} is not in the subpath of {!r}"
ValueError: '\\server01\myfile.pdf\' is not in the subpath of '\server01' OR one path is relative and the other is absolute.

都是绝对路径,path_a肯定是相对于path_b

有效的 UNC 路径必须包含两个或更多路径组件。因此 \server01\myfile.pdf 不是有效的 UNC 路径。

来自规范: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dfsc/149a3039-98ce-491a-9268-2f5ddef08192

A UNC path can be used to access network resources, and MUST be in the format specified by the Universal Naming Convention.

<servername>, <share> and <filename> are referred to as "pathname components" or "path components". A valid UNC path MUST contain two or more path components. <servername> is referred to as the "first pathname component", <share> as the "second pathname component", and so on. The last component of the path is also referred to as the "leaf component".