第十章:使用进程、线程和协程提供并发性-subprocess:创建附加进程-连接管道段

10.1.3 连接管道段
多个命令可以连接一个管线(pipeline),这类似于UNIX shell的做法,即创建单独的Popen实例,把它们的输入和输出串链在一起,一个Popen实例的stdout属性被用作管线中下一个Popen实例的stdin参数,而不是常量PIPE。输出从管线中最后一个命令的stdout句柄读取。

import subprocess

cat = subprocess.Popen(
    ['cat','index.rst'],
    stdout=subprocess.PIPE,
    )

grep = subprocess.Popen(
    ['grep','..literalinclude::'],
    stdin=cat.stdout,
    stdout=subprocess.PIPE,
    )

cut = subprocess.Popen(
    ['cat','-f','3','-d:'],
    stdin=grep.stdout,
    stdout=subprocess.PIPE,
    )

end_of_pipe = cut.stdout

print('Included files:')
for line in end_of_pipe:
    print(line.decode('utf-8').strip())

这个例子重新生成以下命令行:
cat index.rst | grep “…literalinclude” | cut -f 3 -d:
这个管线读取这一节的reStructuredText源文件,并查找所有包含其他文件的文本行。然后打印出所包含的这些文件的文件名。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43193719/article/details/89477222