2011-12-25 42 views
5

我有以下的Python行:Python的子進程擊:花括號

import subprocess 
subprocess.Popen("egrep -r --exclude=*{.git,.svn}* \"text\" ~/directory", stdout=subprocess.PIPE, shell=True).communicate()[0] 

不幸的是,bash中完全忽略--exclude = * {GIT中,使用svn。} *標誌。

我已經將問題縮小到大括號。 --exclude = *。git *將通過python的popen工作,但是當引入花括號時,我無可奈何。有什麼建議麼?

注意:我嘗試使用Python的命令庫運行命令,它會產生完全相同的輸出 - 並且完全相同的忽略--exclude標誌。

回答

2

我猜測它可能是shell逃脫?

這可能是最好的做你自己分裂的參數,並完全避免殼?

import subprocess 
subprocess.Popen(["egrep","-r","--exclude=*{.git,.svn}*","text","~/directory"], stdout=subprocess.PIPE).communicate()[0] 

注意:您可能必須展開~,我不確定。

或者如果bash應該是擴大大括號,那麼你可以做到這一點在Python:

excludes = ['.git','.svn'] 
command = ['egrep','-r'] 
for e in excludes: 
    command.append('--exclude=*%s*'%e) 
command += ["text","~/directory"] 
subprocess.Popen(command, stdout=subprocess.PIPE).communicate()[0] 
+0

這個和指定bash shell的工作很好! – user1115304 2012-01-06 00:37:54

3

當你通過殼=真,蟒蛇轉換命令/bin/sh -c <command>(如描述here)。/bin/sh顯然不支持大括號擴展。你可以嘗試,而不是執行以下操作:

import subprocess 
subprocess.Popen(["/bin/bash", "-c", "egrep -r --exclude=*{.git,.svn}* \"text\" ~/directory"], stdout=subprocess.PIPE).communicate()[0] 
+0

這兩個和分裂的論點,以避免外殼工程太棒了! – user1115304 2012-01-06 00:38:08

0

需要引用該表達式保持慶典從評估其對當前的工作目錄,當你火它關閉。假設您正在查找「文本」(帶引號),那麼您的搜索術語也存在一個錯誤。您的轉義將引號導入Python字符串,但需要再次完成才能讓shell看到它們。

I.e. ... --exclude='*{.git,.svn}*' \\\"text\\\" ...

0

從一個Python POPEN的角度來看,你有什麼wrotten作品,只要你捕捉一個Python變量輸出:

import subprocess 
myOutput = subprocess.Popen("egrep -r --exclude=*{.git,.svn}* \"text\" ~/directory", stdout=subprocess.PIPE, shell=True).communicate()[0] 
print "Output: ", myOutput 

我已經與bash作爲默認的shell命令終端測試,並效果很好。

請注意'grep -E'應該比'egrep'更受歡迎,現在已被棄用。

你當然知道\也是Bash的逃生角色,不是嗎?我的意思是,'*'和花括號是由Bash消耗的,因此不會轉交給grep。所以你應該逃避它們。

grep -Er --exclude=\*\{.git,.svn\}\* \"text\" ~/directory