如何使用子进程。通过管道连接多个进程?

如何使用子进程。通过管道连接多个进程?

如何使用Python执行以下shell命令subprocess模块?

echo "input data" | awk -f script.awk | sort > outfile.txt

输入数据将来自字符串,因此我实际上不需要echo..我已经走了这么远,有人能解释一下我是怎么把它吹过的吗?sort也是?

p_awk = subprocess.Popen(["awk","-f","script.awk"],
                          stdin=subprocess.PIPE,
                          stdout=file("outfile.txt", "w"))p_awk.communicate( "input data" )

更新:请注意,虽然下面接受的答案并没有真正回答问题,但我相信S.Lott是对的,最好避免在一开始就解决这个问题!


繁星点点滴滴
浏览 553回答 3
3回答

海绵宝宝撒

import subprocess some_string = b'input_data'sort_out = open('outfile.txt', 'wb', 0)sort_in = subprocess.Popen('sort',  stdin=subprocess.PIPE, stdout=sort_out).stdin subprocess.Popen(['awk', '-f', 'script.awk'], stdout=sort_in,                   stdin=subprocess.PIPE).communicate(some_string)

catspeake

若要模拟外壳管道,请执行以下操作:from&nbsp;subprocess&nbsp;import&nbsp;check_call check_call('echo&nbsp;"input&nbsp;data"&nbsp;|&nbsp;a&nbsp;|&nbsp;b&nbsp;>&nbsp;outfile.txt',&nbsp;shell=True)而不调用shell(请参见17.1.4.2.换壳管线):#!/usr/bin/env&nbsp;pythonfrom&nbsp;subprocess&nbsp;import&nbsp;Popen,&nbsp;PIPE a&nbsp;=&nbsp;Popen(["a"],&nbsp;stdin=PIPE,&nbsp;stdout=PIPE)with&nbsp;a.stdin: &nbsp;&nbsp;&nbsp;&nbsp;with&nbsp;a.stdout,&nbsp;open("outfile.txt",&nbsp;"wb")&nbsp;as&nbsp;outfile: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;b&nbsp;=&nbsp;Popen(["b"],&nbsp;stdin=a.stdout,&nbsp;stdout=outfile) &nbsp;&nbsp;&nbsp;&nbsp;a.stdin.write(b"input&nbsp;data")statuses&nbsp;=&nbsp;[a.wait(),&nbsp;b.wait()]&nbsp;#&nbsp;both&nbsp;a.stdin/stdout&nbsp;are&nbsp;closed&nbsp;alreadyplumbum提供一些语法糖:#!/usr/bin/env&nbsp;pythonfrom&nbsp;plumbum.cmd&nbsp;import&nbsp;a,&nbsp;b&nbsp;#&nbsp;magic(a&nbsp;<<&nbsp;"input&nbsp;data"&nbsp;|&nbsp;b&nbsp;>&nbsp;"outfile.txt")()模拟:#!/bin/shecho&nbsp;"input&nbsp;data"&nbsp;|&nbsp;awk&nbsp;-f&nbsp;script.awk&nbsp;|&nbsp;sort&nbsp;>&nbsp;outfile.txt是:#!/usr/bin/env&nbsp;pythonfrom&nbsp;plumbum.cmd&nbsp;import&nbsp;awk,&nbsp;sort(awk["-f",&nbsp;"script.awk"]&nbsp;<<&nbsp;"input&nbsp;data"&nbsp;|&nbsp;sort&nbsp;>&nbsp;"outfile.txt")()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python