【问题标题】:python popen pipe in looppython在循环中弹出管道
【发布时间】:2016-07-27 13:10:28
【问题描述】:

我正在尝试编写一个函数来在循环中创建一个 shell 管道,该管道从列表中获取其命令参数并将最后一个标准输出通过管道传输到新的标准输入。 在命令列表的 and 处,我想调用 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

【问题讨论】:

    标签: python python-2.7 subprocess popen


    【解决方案1】:

    问题在于 grep %SESSIONNAME%。当您在命令行上执行相同的操作时,%SESSIONNAME% 实际上被“控制台”取代。 但是当在 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>
    

    如果有帮助请告诉我。

    【讨论】:

    • 我刚刚将 Console 替换为 os.environ["SESSIONNAME"]) 但效果很好。谢谢!
    猜你喜欢
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    相关资源
    最近更新 更多