解决sys.path和os.path.join中的混合斜杠

时间:2014-09-03 15:29:11

标签: python portability arcpy sys

我需要解决sys.path提供的分隔符与os.path.join正在使用的分隔符之间的差异。

我模仿了这个Esri方法(Techniques for sharing Python scripts)以使我的脚本可移植。它现在在Windows中使用,但最终将存在于Linux服务器上;我需要让Python确定合适的斜杠。

他们的建议:

# Get the pathname to this script
scriptPath = sys.path[0]

# Get the pathname to the ToolShare folder
toolSharePath = os.path.dirname(scriptPath)

# Now construct pathname to the ToolData folder
toolDataPath = os.path.join(toolSharePath, "ToolData")
print "ToolData folder: " + toolDataPath

但这会输出ToolData folder: C:/gis\ToolData - 显然混合斜线无法正常工作。

本课题(mixed slashes with os.path.join on windows)包括解决方案的基本方法:

  

在将其输入os.path.join之前检查您的外部输入(您显然不控制格式的输入)。这样,您可以确保os.path.join不会根据可能的错误输入做出错误的决定

但是,我不确定如何确保它可以跨平台工作。如果我在.replace("/","\\")结果上使用sys.path[0],这对Windows来说非常棒,但是一旦我转换到Unix,这不会导致相同的混合斜杠问题吗?

3 个答案:

答案 0 :(得分:3)

如何使用os.path.normpath()

>>> import os
>>> os.path.normpath(r'c:\my/path\to/something.py')
'c:\\my\\path\\to\\something.py'

另外值得一提的是:Windows路径API不关心是使用正斜杠还是反斜杠。通常这是程序的错误,不能正确处理削减。例如,在python中:

with open(r'c:/path/to/my/file.py') as f:
    print f.read()

会奏效。

答案 1 :(得分:1)

reading the documentation之后尝试了很多变化:

os.path.abspath函数可以“清除”斜杠,因此斜杠sys.path[0]决定使用哪个方向,斜杠将替换为首选分隔符。

scriptPath = sys.path[0]
toolDataPath = os.path.join(scriptPath, "ToolData")

结果:C:/gis\ToolData

scriptPath = sys.path[0]
toolSharePath = os.path.abspath(scriptPath)
# or, in one line: toolSharePath = os.path.abspath(sys.path[0])
toolDataPath = os.path.join(toolSharePath, "ToolData")

结果:C:\gis\ToolData

答案 2 :(得分:0)

Python中有一个os.sep字符,用于存储操作系统首选的文件夹分隔字符。也许您可以使用它来执行手动字符串join

在Linux上:

>>> import os
>>> os.sep
'/'

https://docs.python.org/2/library/os.html#os.sep