Ruby管道:如何将两个子流程的输出绑定在一起? [英] Ruby pipes: How do I tie the output of two subprocesses together?
问题描述
是否有自动化的方法在Ruby中进行外壳管道?我正在尝试将以下shell代码转换为Ruby:
Is there an automated way to do shell piping in Ruby? I'm trying to convert the following shell code to Ruby:
a | b | c... > ...
但是到目前为止,我发现的唯一解决方案是自己进行缓冲区管理(简化,未经测试,希望可以理解我的意思):
but the only solution I have found so far is to do the buffer management myself (simplified, untested, hope it gets my meaning across):
a = IO.popen('a')
b = IO.popen('b', 'w+')
Thread.new(a, b) { |in, out|
out.write(in.readpartial(4096)) until in.eof?
out.close_write
}
# deal with b.read...
我猜我正在寻找一种告诉Popen使用现有流而不是创建新流的方法?或者,使用IO#merge方法将a的输出连接到b的输入?当过滤器数量增加时,我当前的方法变得相当笨拙.
I guess what I'm looking for is a way to tell popen to use an existing stream, instead of creating a new one? Or alternatively, an IO#merge method to connect a's output to b's input? My current approach becomes rather unwieldly when the number of filters grows.
我显然了解Kernel#system('a | b')
,但是我需要以通用的方式将Ruby过滤器与外部程序过滤器混合.
I know about Kernel#system('a | b')
obviously, but I need to mix Ruby filters with external program filters in a generic way.
推荐答案
旧问题,但由于它是Google的第一个结果之一,因此,答案如下:
Old question, but since its one of the first result on Google, here is the answer : http://devver.wordpress.com/2009/10/12/ruby-subprocesses-part_3/ (method 8)
简而言之:
sh = Shell.new
sh.system("a") | sh.system("b") | sh.system("c")
您可以做更复杂的事情,例如
And you can do more complicated things like
sh.echo(my_string) | sh.system("wc") > "file_path"
xml = (sh.echo(html) | sh.system("tidy", "-q")).to_s
这篇关于Ruby管道:如何将两个子流程的输出绑定在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!