2015-09-18 142 views
0

我真正想要的運行是xargs的和管道如同在Python 2.6以下shell命令,如何使用管道在Python運行shell命令xargs的2.6

grep -lsr "somestring" ./somedir | xargs rm 

我想與刪除./somedir所有文件內容匹配somestring

我嘗試了下面的代碼,但它不工作。感謝您的任何意見。

import subprocess 

    p1 = subprocess.Popen('grep -lsr "somestring" ./somedir', stdout=subprocess.PIPE, shell=True) 
    p2 = subprocess.Popen('xargs rm', stdin=p1.stdout, stdout=subprocess.PIPE, shell=True) 
    p1.stdout.close() 
    output = p2.communicate()[0] 

錯誤我越來越:

rm: missing operand 
Try `rm --help' for more information. 

回答

0

當使用shell = True時,第一個參數POPEN應該只是一個字符串不是列表。

你也可以只運行

subprocess.check_call("grep -lsr "somestring" ./somedir | xargs rm", shell=True) 
+0

修正了拼寫錯誤。編輯帖子。試過你的解決方案。仍然收到錯誤「rm:丟失操作數」。順便說一句,我使用Python 2.6,我無法親自更改。 – kevinlu

+0

您是否只運行grep部分並確保它正在打印您期望看到的文件? –

+0

試圖運行subprocess.check_call('grep -lsr「somestring」./somedir',shell = True)。有錯誤:subprocess.CalledProcessError:命令'grep -lsr「somestring」./somedir'返回非零退出狀態1 – kevinlu