2014-09-03 82 views
0

我需要解析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後,是不是會導致相同的混合斜線問題?

+0

'pathlib'是一個選項嗎?它在Python 3.4中是新的,在Python 2.7中不存在。 – chepner 2014-09-03 15:43:23

+0

因爲我使用了一堆ArcPy函數(和/或我們在服務器上只有2.7個),所以我_think_認爲我被Python 2.7困住了。 – Erica 2014-09-03 15:44:44

+0

Python可以對Windows路徑使用正斜槓,所以'sys.path [0] .replace(r'\','/')'可能是您跨平臺功能的最佳選擇。 – chepner 2014-09-03 15:48:17

回答

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

0

Python中有一個os.sep字符,用於存儲操作系統首選的文件夾分隔字符。也許你可以使用它來執行手動字符串join

在Linux上:

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

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

+2

問題是'os.sep'(在Windows中是一個反斜槓)與'sys.path [0]'正在使用的內容(正斜槓)不匹配。它可能在Linux上執行(沒有檢查過),但我希望它在任一平臺上都能夠乾淨地運行。 – Erica 2014-09-03 15:40:03

1

如何使用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() 

將工作。