2015-09-18 102 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