如何使用子进程。通过管道连接多个进程?如何使用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是对的,最好避免在一开始就解决这个问题!
3 回答
海绵宝宝撒
TA贡献1809条经验 获得超8个赞
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
TA贡献1111条经验 获得超0个赞
from subprocess import check_call check_call('echo "input data" | a | b > outfile.txt', shell=True)
#!/usr/bin/env pythonfrom subprocess import Popen, PIPE a = Popen(["a"], stdin=PIPE, stdout=PIPE)with a.stdin: with a.stdout, open("outfile.txt", "wb") as outfile: b = Popen(["b"], stdin=a.stdout, stdout=outfile) a.stdin.write(b"input data")statuses = [a.wait(), b.wait()] # both a.stdin/stdout are closed already
plumbum
#!/usr/bin/env pythonfrom plumbum.cmd import a, b # magic(a << "input data" | b > "outfile.txt")()
#!/bin/shecho "input data" | awk -f script.awk | sort > outfile.txt
#!/usr/bin/env pythonfrom plumbum.cmd import awk, sort(awk["-f", "script.awk"] << "input data" | sort > "outfile.txt")()
添加回答
举报
0/150
提交
取消