我有一個bash片段,我想移植到Python。它發現SVN的位置以及它是否可執行。如何在Python中使用這個bash測試構造?
SVN=`which svn 2>&1`
if [[ ! -x $SVN ]]; then
echo "A subversion binary could not be found ($SVN)"
fi
下面是一個使用子模塊在Python我當前的嘗試:
SVN = Popen('which svn 2>&1', shell=True, stdout=PIPE).communicate()[0]
Popen("if [[ ! -x SVN ]]; then echo 'svn could not be found or executed'; fi", shell=True)
這不,因爲雖然我有SVN的位置保存在Python的本地命名空間的工作,我可以」從Popen訪問它。
我也試圖組合成一個POPEN對象:
Popen("if [[ ! -x 'which svn 2>&1']]; then echo 'svn could not be found'; fi", shell=True)
,但我得到這個錯誤(不用說,看起來很笨重)
/bin/sh: -c: line 0: syntax error near `;'
/bin/sh: -c: line 0: `if [[ ! -x 'which svn 2>&1']]; then echo 'svn could not be found'; fi'
有一個測試的Python版本構造「-x」?我認爲這將是理想的。其他解決方法也將受到讚賞。
由於
[此網站](http://ubuntuforums.org/showthread.php?t=1457094)提供了一個代碼段,看起來像'commands.getoutput(「如果[-x MYFILE] \ n然後回聲真\ NFI「)'。然而,由於您仍在調用Bash,因此這很難「移植到Python」。 – Kos 2013-03-11 07:14:04
'os.stat'可以給你關於給定文件的一些信息,比如它的權限,但是我認爲你仍然需要爲它建立一個「可執行的當前用戶」測試。 – Kos 2013-03-11 07:16:17
您可以先將bash命令存儲爲字符串,以便您可以將它與變量SVN連接起來?然後將其傳遞給Popen()... – Jeff 2013-03-11 07:16:58