python popen pipe in loop

I'm trying to write a function to create a shell pipeline in a loop that gets its command parameters from a list and pipes the last stdout to the new stdin. At the and of the command list, I want to call the communicate method on the Popen object to get the output.

The output is always empty. What am I doing wrong?

See following example:

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]

I'm on a Windows environment with additional unix functions. Following command works on my Windows command line and should be written to strProcessInfo:

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

The problem is with grep %SESSIONNAME%. When you execute same thing on commandline, the %SESSIONNAME% is actually getting replaced by "Console". But when executed in python script, it is not getting replaced. It is trying to find exact %SESSIONNAME% which is not present. That's why output is blank.

Below is code.

Grep replaced by findstr and %SESSIONNAME% replaced by word "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

Output:

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


C:Usersdinesh_pundkarDesktop>

Please let me know if it is helpful.

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

上一篇: Python子进程模块命令行程序

下一篇: 循环中的python popen管道