python - 在 Python 中解决进程链

标签 python subprocess pipe

我正在尝试编写一个实用程序,它将在 Python 中无缝地将无限数量的命令组合在一起。到目前为止,这是我在 the documentation on piping in subprocess 之后得出的结论:

from subprocess import Popen, PIPE, STDOUT

def taskchain(argset, result=STDOUT):
    lastprocess = None

    for index, args in enumerate(argset): # expected to be a list containing lists
        process = Popen(args, stdout=stdout if index == (len(argset)-1) else PIPE,
            stdin=None if lastprocess is None else lastprocess.stdout)

        if lastprocess is not None:
            lastprocess.stdout.close()

        lastprocess = process

    if stdout == PIPE:
        return lastprocess.communicate()[0]
    else:
        lastprocess.wait()

请注意,我没有使用 shell=True 来避免那里的安全问题。

不幸的是,这不起作用,因为我得到:

OSError: [Errno 9] Baf file descriptor

我不确定什么似乎失败了。有人可以帮我写一个方法来为无限数量的子流程实现流程链接吗?

(用例是这样的:taskchain([('ps', 'aux'), ('grep', 'python'), ('cut', '-b', '1') ]).)

最佳答案

stdout=stdout if argset.index(args) == (len(args) - 1) else PIPE)

应该是这样

stdout=stdout if argset.index(args) == (len(argset) - 1) else PIPE)

你最好使用 enumerate 而不是 argset.index

此外,您需要将子流程相互连接:

..., stdin=None if lastprocess is None else lastprocess.stdout)

最后,STDOUT 仅作为 stderr 参数的参数有效;要通过标准输出,您应该通过 stdout=None

关于python - 在 Python 中解决进程链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19733768/

相关文章:

python - 在 Pandas 中使用 groupby 查找重复项

python - 安装 askbot 后 Django 应用程序未运行

python - 如何在 aws lambda/tmp 目录中运行 python 脚本

c++ - 如何像输入 "cat | tr a-z A-Z"一样重复写入,然后从管道读取,

java - 在 C++ 中 fork 一个新进程并执行一个 .jar 文件

Python 3 - 查找列表的哪个索引包含特定字符串作为子字符串

python - 如何调试 PyQt 崩溃?

java - Python脚本使用子进程运行java程序时出现java错误后需要继续

Python函数捕获子进程stdout和stderr到日志文件

bash - Bash 中的条件流水线