Ela*_*ron 4 python pathlib python-3.8
在 Python3.8 上,我尝试使用pathlib将字符串连接到远程计算机 C 驱动器上的 UNC 路径。
这是奇怪的不一致。
例如:
>>> remote = Path("\\\\remote\\", "C$\\Some\\Path")
>>> remote
WindowsPath('//remote//C$/Some/Path')
>>> remote2 = Path(remote, "More")
>>> remote2
WindowsPath('/remote/C$/Some/Path/More')
Run Code Online (Sandbox Code Playgroud)
注意首字母//是如何变成的吗/?
不过,将初始路径放在一行中,一切都很好:
>>> remote = Path("\\\\remote\\C$\\Some\\Path")
>>> remote
WindowsPath('//remote/C$/Some/Path')
>>> remote2 = Path(remote, "more")
>>> remote2
WindowsPath('//remote/C$/Some/Path/more')
Run Code Online (Sandbox Code Playgroud)
这是一种解决方法,但我怀疑我误解了它应该如何工作或做错了。
有人知道发生了什么事吗?
tldr:您应该将整个 UNC 共享 ( \\\\host\\share) 作为一个单元,pathlib对 UNC 路径进行特殊情况处理,但它特别需要此前缀才能将路径识别为 UNC。你不能使用pathlib的设施来单独管理主机和共享,这会让pathlib大吃一惊。
Path 构造函数规范化(删除重复)路径分隔符:
>>> PPP('///foo//bar////qux')
PurePosixPath('/foo/bar/qux')
>>> PWP('///foo//bar////qux')
PureWindowsPath('/foo/bar/qux')
Run Code Online (Sandbox Code Playgroud)
PureWindowsPath 对于被识别为 UNC 的路径有一个特殊情况,即//host/share...避免折叠前导分隔符。
然而,您最初的串联将其置于一个奇怪的恐惧之中,因为它创建了一个表单路径//host//share...,然后该路径在传递给构造函数时被转换回字符串,此时它不再与 UNC 匹配,并且所有分隔符都会折叠:
>>> PWP("\\\\remote\\", "C$\\Some\\Path")
PureWindowsPath('//remote//C$/Some/Path')
>>> str(PWP("\\\\remote\\", "C$\\Some\\Path"))
'\\\\remote\\\\C$\\Some\\Path'
>>> PWP(str(PWP("\\\\remote\\", "C$\\Some\\Path")))
PureWindowsPath('/remote/C$/Some/Path')
Run Code Online (Sandbox Code Playgroud)
这个问题似乎具体是在看起来 UNC 的路径上存在尾随分隔符,我不知道这是否是一个错误,或者它是否与其他一些 UNC 样式(但不是 UNC)特殊情况匹配:
>>> PWP("//remote")
PureWindowsPath('/remote')
>>> PWP("//remote/")
PureWindowsPath('//remote//') # this one is weird, the trailing separator gets doubled which breaks everything
>>> PWP("//remote/foo")
PureWindowsPath('//remote/foo/')
>>> PWP("//remote//foo")
PureWindowsPath('/remote/foo')
Run Code Online (Sandbox Code Playgroud)
这些行为似乎并没有真正记录下来,pathlib 文档特别指出它折叠了路径分隔符,并且有一些 UNC 示例表明它没有,但我真的不知道到底应该发生什么。无论哪种方式,如果前两个段保留为单个“驱动器”单元,并且共享路径被视为驱动器,则它似乎只能在某种程度上正确处理 UNC 路径,并且有专门记录。
值得注意的是:使用joinpath//似乎不会触发重新规范化,您的路径仍然不正确(因为主机和共享之间的第二个路径仍然加倍),但它并没有完全崩溃。