2016-01-04 250 views
0

在Windows上运行于Python 2.7.10上。python isabs无法将Windows UNC路径识别为绝对路径

> os.path.isabs(r"\\\unc_path\file") 
False 

> os.path.isabs(r"\\\unc_path\") 
False 

这是故意的吗?

+2

请提供您正在测试的字面路径名。您列出的路径不是UNC路径,因为它们不带有双反斜线。 –

+0

难道你不需要一个设备来做出绝对的? 'os.path.isabs(r“c:\ unc_path \ file”)'或os.path.isabs(r“\\ unc_path \ file”) – Vatine

+0

此外,请参阅[此处]的注释(https:// docs。 python.org/2/library/os.path.html#module-os.path):“*注意在Windows上,许多这些函数不能正确支持UNC路径名。*” –

回答

0

您需要注意字符串转义,通常使用\

例如\n是换行符号。 \\产生斜杠\

因此,字符串"\\something"将打印为\something

如果您想要内容\\something您需要键入\\\\something,即双任何反斜杠。或者,您可以使用原始字符串r"\\something"也可以使用。你不能在那里再输入一个换行符,但是你的路径名中没有它们。

因此,您键入的路径名称可能不是您认为的那样。 \是一个特殊的字符,不幸的是微软在DOS时代认为这将是一个很好的角色,用作路径分隔符。 Unix操作系统(其中大多数编程语言和使用\escape character的约定始发)使用正斜杠/,这是没有问题的。

0

os.path.isabs如果在\\server\share部件后面存在某些路径信息(即使只是一个斜杠),它将只返回一个UNC路径的True

Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import os 
>>> os.path.isabs('\\\\server\\share') 
False 
>>> os.path.isabs('\\\\server\\share\\') 
True 

要理解为什么,它有助于理解isabs是代码对splitdrive顶部只是一点点。在ntpath,Windows实现的os.path,它看起来像这样:

def isabs(s): 
    """Test whether a path is absolute""" 
    s = splitdrive(s)[1] 
    return s != '' and s[:1] in '/\\' 

splitdrive实施旨在处理与驱动器号和UNC路径两个路径,并在它们之间一定的一致性。为ntpath.splitdrive文件说:

如果路径中包含驱动器盘符,drive_or_unc将包含 一切都交给了冒号。例如splitdrive(“C:/目录”) 返回(“C:”,“/目录”)

如果路径中包含一个UNC路径,该drive_or_unc将包含 主机名和共享直到但不包括第四个目录 分隔符。例如splitdrive( “//主机/电脑/目录”)返回 ( “//主机/计算机”, “/目录”)

所以......

>>> os.path.splitdrive('\\\\server\\share') 
('\\\\server\\share', '') 

你可以看到isabs将返回False

话虽这么说,这种行为的Python 2.7.7和Python 2.7.8之间的变化:

Python 2.7.7 (default, Oct 12 2015, 14:42:48) [MSC v.1500 64 bit (AMD64)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import os 
>>> os.path.isabs('\\\\server\\share') 
True 
>>> os.path.isabs('\\\\server\\share\\') 
True 

的变化是修复在os.path.join一个bug。我不能完全肯定,如果Python开发人员意识到这将是一段os.path功能的重大更改,但行为是使用Python 3.5一致:

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import os 
>>> os.path.isabs('\\\\server\\share') 
False 
>>> os.path.isabs('\\\\server\\share\\') 
True