我需要解析sys.path提供的分隔符和os.path.join正在使用的分隔符之间的不一致。从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
不会根据可能的错误输入做出错误的决定。
但是,我不确定如何确保它能够跨平台工作。如果我在sys.path[0]
结果上使用.replace("/","\\")
,这对于Windows非常适用,但是一旦我转换到Unix后,是不是会导致相同的混合斜线问题?
'pathlib'是一个选项吗?它在Python 3.4中是新的,在Python 2.7中不存在。 – chepner 2014-09-03 15:43:23
因为我使用了一堆ArcPy函数(和/或我们在服务器上只有2.7个),所以我_think_认为我被Python 2.7困住了。 – Erica 2014-09-03 15:44:44
Python可以对Windows路径使用正斜杠,所以'sys.path [0] .replace(r'\','/')'可能是您跨平台功能的最佳选择。 – chepner 2014-09-03 15:48:17