python 循环打开管道

python popen pipe in loop

我正在尝试编写一个函数来在循环中创建一个 shell 管道,该管道从列表中获取其命令参数并将最后一个标准输出通过管道传输到新的标准输入。 在命令列表的and处,我想调用Popen对象的communicate方法来获取输出。

输出始终为空。我做错了什么?

参见以下示例:

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% 实际上被替换为 "Console"。 但是在 python 脚本中执行时,它不会被替换。它试图找到不存在的确切 %SESSIONNAME%。这就是输出为空白的原因。

下面是代码。

Grep 替换为 findstr 并且 %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:\Users\dinesh_pundkar\Desktop>python abc.py
tasklist.exe                 12316 Console                    1      7,856 K


C:\Users\dinesh_pundkar\Desktop>

如果有帮助,请告诉我。