循环中的python popen管道

我试图编写一个函数在循环中创建一个shell管道,从一个列表中获取其命令参数,并将最后一个stdout传递给新的stdin。 在命令列表中,我想调用Popen对象的通信方法来获取输出。

输出总是空的。 我究竟做错了什么?

看下面的例子:

lstCmd = ["tasklist", "grep %SESSIONNAME%", "grep %s" % (strAutName)]
lstPopen = [subprocess.Popen(lstCmd[0].split(), stdout=subprocess.PIPE)]
    for i in range(len(lstCmd) - 1):
        lstPopen.append(subprocess.Popen(lstCmd[i + 1].split(), stdin=lstPopen[i].stdout, stdout=subprocess.PIPE))
        lstPopen[i].stdout.close()
strProcessInfo = lstPopen[-1].communicate()[0]

我在使用其他unix函数的Windows环境中。 以下命令在我的Windows命令行上工作,并应写入strProcessInfo:

C:>tasklist | grep %SESSIONNAME% | grep tasklist
tasklist.exe                 18112 Console                    1         5.948 K

问题在于grep%SESSIONNAME%。 当你在命令行执行同样的事情时,%SESSIONNAME%实际上被“控制台”取代。 但是当在python脚本中执行时,它不会被替换。 它试图找到不存在的确切%SESSIONNAME%。 这就是输出为空的原因。

以下是代码。

Grepfindstr%SESSIONNAME%替换为单词“Console”替换。

import sys
import subprocess

lstCmd = ["tasklist", "findstr Console","findstr tasklist"]
lstPopen = [subprocess.Popen(lstCmd[0].split(), stdout=subprocess.PIPE)]
for i in range(len(lstCmd) - 1):
    lstPopen.append(subprocess.Popen(lstCmd[i + 1].split(), stdin=lstPopen[i].stdout, stdout=subprocess.PIPE))
    lstPopen[i].stdout.close()

strProcessInfo = lstPopen[-1].communicate()[0]
print strProcessInfo

输出:

C:Usersdinesh_pundkarDesktop>python abc.py
tasklist.exe                 12316 Console                    1      7,856 K


C:Usersdinesh_pundkarDesktop>

请让我知道它是否有帮助。

链接地址: http://www.djcxy.com/p/13483.html

上一篇: python popen pipe in loop

下一篇: Output of subprocess both to PIPE and directly to stdout