我需要解析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