python popen循环管道

2024-10-04 11:31:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个函数,在一个循环中创建一个shell管道,该管道从列表中获取命令参数,并将最后一个stdout管道发送到新的stdin。 在命令列表的和处,我想调用Popen对象上的communication方法来获得输出。在

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

参见以下示例:

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:

^{pr2}$

Tags: 函数命令列表管道windowsstdinstdoutgrep
1条回答
网友
1楼 · 发布于 2024-10-04 11:31:28

问题出在grep%SESSIONNAME%上。当您在命令行上执行相同的操作时,实际上将%SESSIONNAME%替换为“Console”。 但在python脚本中执行时,它不会被替换。它正在尝试查找不存在的确切%SESSIONNAME%。这就是为什么输出是空白的。在

下面是代码。在

Grep替换为findstr,并将%SESSIONNAME%替换为word“控制台”。在

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

输出:

^{pr2}$

如果有用请告诉我。在

相关问题 更多 >