小编Pla*_*lan的帖子

Python子进程模块,如何为第一个管道命令系列提供输入?

我正在尝试使用Python的子进程模块.我需要的是将输入发送到第一个进程,其输出成为第二个进程的输入.这种情况基本上与这里的文档中给出的示例几乎相同:http: //docs.python.org/library/subprocess.html#replacing-shell-pipeline, 除了我需要提供输入第一个命令.这是复制的示例:

p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
Run Code Online (Sandbox Code Playgroud)

如果我们将第一行更改为:

p1 = Popen(["cat"], stdout=PIPE, stdin=PIPE)
Run Code Online (Sandbox Code Playgroud)

如何为进程提供输入字符串?如果我通过将最后一行更改为:

output = p2.communicate(input=inputstring)[0]
Run Code Online (Sandbox Code Playgroud)

这不起作用.

我有一个工作版本,它只将第一个命令的输出存储在一个字符串中,然后将其传递给第二个命令.这并不可怕,因为基本上没有可以被利用的并发性(在我的实际用例中,第一个命令将很快退出并在最后生成所有输出).这是完整的工作版本:

import subprocess

simple = """Writing some text
with some lines in which the
word line occurs but others
where it does
not
"""

def run ():
  catcommand = [ "cat" ]
  catprocess = subprocess.Popen(catcommand,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
  (catout, caterr) …
Run Code Online (Sandbox Code Playgroud)

python subprocess pipe

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

pipe ×1

python ×1

subprocess ×1