使用“循环”遍历stdout命令行内容;findstr“;在Python和Windows7中

使用“循环”遍历stdout命令行内容;findstr“;在Python和Windows7中,python,subprocess,windows-7-x64,Python,Subprocess,Windows 7 X64,我正在编写一个python脚本,它使用Windows命令行向设备发送命令,然后读取输出并迭代其内容: proc = subprocess.Popen("adb logcat | findstr Test", stdout=subprocess.PIPE) for line in proc.stdout: if "stopped" in line: print line print "Test Service finished \n" bre

我正在编写一个python脚本,它使用Windows命令行向设备发送命令,然后读取输出并迭代其内容:

proc = subprocess.Popen("adb logcat | findstr Test", stdout=subprocess.PIPE)
for line in proc.stdout:
    if "stopped" in line:
        print line
        print "Test Service finished \n"
        break
    else:
        print line
不幸的是,我得到了以下信息:

>>> 
/system/bin/sh: findstr: not found
output error: Broken pipe
在没有“findstr Gps”的情况下,它可以工作,但是发送到管道的输出量太大,最终导致内存事件

你知道我做错了什么吗

提前谢谢

我认为这可能有效(不确定是否确实需要
stderr=subprocess.PIPE
,尽管它应该不会有什么坏处):


for line…
循环之前添加一个
proc.communicate()
。谢谢,现在的结果是:回溯(最近一次调用):文件“C:/Python27/junk.py”,第20行,在proc.stdout中的for line:ValueError:I/O操作对关闭的文件
communicate()
返回一个元组
(stdoutdata,stderdata)
,因此,将
for
循环更改为从
stdoutdata
读取,而不是
proc.stdout
——很抱歉,我不确定是否需要这样做,所以我没有提及。我不确定如何更改“proc.stdout中的for行”部分。我是否还应该更改进程定义:“进程=子进程.Popen(mycommand,stdout=subprocess.PIPE,stderr=subprocess.PIPE)”?提前感谢不幸的是,我仍然得到相同的响应:>>>/system/bin/sh:findstr:未找到输出错误:管道中断不幸的是,我仍然得到相同的响应:>>>/system/bin/sh:findstr:未找到输出错误:管道中断。这是否与smth无关?我的意思是,popen是否会因为找不到findstr而无法提交cmd命令?我想我知道问题是什么:
findstr
不是一个过滤器——它不从stdin读取,因此不能与管道一起使用。您需要改用
find
命令,如果未指定文件名,该命令将从stdin读取。它不执行正则表达式,要搜索的文本必须用双引号括起来,即
查找“Test”
。现在的响应是::>>>/system/bin/sh:find:not found输出错误。您可能必须使用它的完整路径,请参见此
proc = subprocess.Popen("adb logcat | findstr Test", stdout=subprocess.PIPE,
                                                     stderr=subprocess.PIPE))
stdoutdata, stderrdata = proc.communicate()
for line in stdoutdata:
    if "stopped" in line:
        print line
        print "Test Service finished \n"
        break
    else:
        print line