蟒蛇

2011-06-04 186 views
1

我已經安裝在我的MAC,我可以用在終端使用下面的命令來編譯HAML文件轉換爲HTML文件的紅寶石寶石「HAML」使用Ruby寶石/命令該命令僅在第二個路徑創建一個html文件,並且在終端中不提供輸出。因此,例如,此命令:蟒蛇

haml "/Volumes/Macintosh HD/Users/me/Sites/ICSP/sugar.haml" "/Volumes/Macintosh HD/Users/me/Sites/ICSP/sugar.html" 

在給定路徑處創建一個sugar.html文件。現在我試圖從python腳本中使用這個功能。當我鍵入此爲IDLE的交互式Python外殼:

>>>import subprocess 
>>>subprocess.Popen('haml "/Volumes/Macintosh HD/Users/me/Sites/ICSP/sugar.haml"  "/Volumes/Macintosh HD/Users/me/Sites/ICSP/sugar.html"', shell=True, executable='/bin/bash') 
<subprocess.Popen object at 0x159d6f0> 

我得到的輸出表明進程已經運行,但沒有輸出文件。這是爲什麼發生?我甚至放入了Shell參數,但沒有出現交互式shell。另外,我在某處讀到,使用的默認shell不是bash,這是Mac終端使用的,所以我把它放在了太好的位置。

按照icktoofay的建議,我跑了check_call。這是我收到的回溯:

Traceback (most recent call last):
File "/Users/neil/Desktop/subprocesstest.py", line 7, in p = subprocess.check_call(x, shell=True) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 504, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command 'haml "/Volumes/Macintosh HD/Users/neil/Sites/ICSP/sugar.haml" "/Volumes/Macintosh HD/Users/neil/Sites/ICSP/sugar.html"' returned non-zero exit status 127

按照bash reference manual,而尋找一個要執行的命令,

If the name is neither a shell function nor a builtin, and contains no slashes, Bash searches each element of $PATH for a directory containing an executable file by that name. ... If that function is not defined, the shell prints an error message and returns an exit status of 127.

但是,我認爲這將後殼確實找到HAML命令和可執行參數,因爲在此之前,它給出'文件或目錄未找到錯誤',這表明該函數不是直接可執行的,而是僅在一個shell中可執行。

現在我該如何讓python找到這個haml命令?或者,我會不得不使用一些醜陋的解決方法,像一個然後調用haml命令的applescript。

+1

您是否嘗試過使用['subprocess.check_call'(http://docs.python.org/library/subprocess.html#subprocess.check_call),而不是直接使用['subprocess.Popen']( http://docs.python.org/library/subprocess.html#subprocess.Popen)? – icktoofay 2011-06-04 20:37:55

+0

對不起,現在這個問題似乎很長時間了,但我試圖提供儘可能多的信息來使調試更容易。 – Neil 2011-06-04 20:59:10

+2

你可能已經嘗試過這樣的事情,但是這個工作(路徑明顯改變了)? 'subprocess.check_call(['/ path/to/haml','/your/file.haml','/your/file.html'])' – icktoofay 2011-06-04 21:03:38

回答

2

我看到你正在使用shell=True,所以我會預期的東西才工作。在這裏用Python 2.7.1和haml 3.1.1在本地檢查它,並且我沒有執行它的問題。還有一些您可能感興趣的python實現,PyHAML,HamlPy,djamldjango-haml

import subprocess 
subprocess.Popen(['haml', 'hello.haml', 'hello.html'], shell=True) 

% cat hello.html 
<strong class='code' id='message'>Hello, World!</strong> 
+0

我確實使用了'shell = True'參數。我會嘗試使用haml的完整路徑,但是由於我猜測這會因計算機而異,因此很難將其轉換爲可分發的腳本。另外,我之前也查了一下python的實現,但看起來他們不僅僅是一個調用haml編譯器的python橋樑,他們實際上處理編譯本身,有時產生與官方haml gem輸出不同的輸出。我寧願不冒險使用未來可能落後於語法支持的python實現。 – Neil 2011-06-05 17:57:19

+0

@尼爾啊我現在看到了。應該只是工作。很奇怪。也許是一個haml的bug?我只是測試它,它對我來說工作得很好。 – zeekay 2011-06-05 18:26:39

0

shlex.split()是你的朋友,當你想建立適合Popen及其同類args名單。

>>> import subprocess 
>>> import shlex 
>>> p = subprocess.Popen(shlex.split('haml "/Volumes/Macintosh HD/Users/me/Sites/ICSP/sugar.haml" "/Volumes/Macintosh HD/Users/me/Sites/ICSP/sugar.html"')) 
>>> p.wait() 
0