<p>该类将使用任意数量的管道运行命令:</p>
<p><strong>管道.py</strong></p>
<pre><code>import shlex
import subprocess
class Pipeline(object):
def __init__(self, command):
self.command = command
self.command_list = self.command.split('|')
self.output = None
self.errors = None
self.status = None
self.result = None
def run(self):
process_list = list()
previous_process = None
for command in self.command_list:
args = shlex.split(command)
if previous_process is None:
process = subprocess.Popen(args, stdout=subprocess.PIPE)
else:
process = subprocess.Popen(args,
stdin=previous_process.stdout,
stdout=subprocess.PIPE)
process_list.append(process)
previous_process = process
last_process = process_list[-1]
self.output, self.errors = last_process.communicate()
self.status = last_process.returncode
self.result = (0 == self.status)
return self.result
</code></pre>
<p>此示例演示如何使用类:</p>
<p><strong>线束.py</strong></p>
^{pr2}$
<p>我为测试创建了以下示例文件:</p>
<p><strong>示例.txt</strong></p>
<pre><code>word1>word2=word3
list1>list2=list3
a>bigstring of word=b
blah1>blah2=blah3
</code></pre>
<p><strong>输出</strong></p>
<pre><code>a smaller b
blah1 blah2 blah3
list1 list2 list3
word1 word2 word3
</code></pre>