2013-07-26 64 views
2

我想下面执行系统命令使用python:使用下面的Python代码Python的不一致标准输出subprocess.popen

cat txt_file | egrep "keyword1|keyword2|keyword3" 

p1 = subprocess.Popen (['cat', txt_file], stdout=subprocess.PIPE) 
p2 = subprocess.Popen (['egrep', "\"" + keyword_list + "\""], stdin=p1.stdout, stdout=subprocess.PIPE) 

#where keyword_list is : "keyword1|keyword2|keyword3" 

p1.stdout.close() #for p2 to exit if SIGPIPE from p1 
out = p2.communicate()[0] 

有多种线路的egrep的输出,但是使用上面的脚本,我只能得到与变量out中的中间关键字2匹配的行。

这里有什么问题?

更新: 平台:窗口 txt_file相当大〜8 MB

回答

0

我猜想这是一个"\""的东西(这看起来更好为'"',BTW)。

要调用Popen()没有shell=True,所以你只要你想他们应该给的参数。在正常的egrep上调用""被外壳剥离,这是您在这里没有的一个步骤。所以你不需要他们在这里。

0

问题通过以下解决方法解决:

#Using file as stdin for p2 
txt_file = open ('txt_file_path') 
p2 = subprocess.Popen (['egrep', keyword_list, stdin=txt_file) 
out = p2.communicate()[0] 
txt_file.close() 
相关问题