[英]Inconsistent stdout on Python subprocess.popen
I'm trying to execute below system command using python : 我正在尝试使用python执行以下系统命令:
cat txt_file | egrep "keyword1|keyword2|keyword3"
using below python code : 使用以下python代码:
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]
There are multiple lines for the egrep output, But using the above script I'm able to get only the line matching the middle keyword2 in the variable out
. egrep输出有多行,但是使用上面的脚本,我仅能获得匹配变量
out
中居中keyword2的out
。
What might be the issue here? 这里可能是什么问题?
Update : Platform : windows txt_file is quite big ~8 MB 更新:平台:Windows txt_file很大〜8 MB
I suppose it is the "\\""
stuff (which would look nicer as '"'
, BTW). 我想这是
"\\""
东西(看起来更好的是'"'
,顺便说一句)。
You are calling Popen()
without shell=True
, so you should give the parameters as you want them. 您在不使用
shell=True
情况下调用Popen()
,因此应根据需要提供参数。 On a normal egrep
call the ""
are stripped away by the shell, a step which you don't have here. 在普通的
egrep
调用中,shell将""
剥离掉了,这是您没有的步骤。 SO you don't need them here. 因此,您在这里不需要它们。
Issue resolved by the following workaround: 通过以下解决方法解决的问题:
#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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.