当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Open3.pipeline_rw用法及代码示例


本文简要介绍ruby语言中 Open3.pipeline_rw 的用法。

用法

pipeline_rw(*cmds, &block)

Open3.pipeline_rw 将命令列表作为管道启动,管道连接到第一个命令的标准输入和最后一个命令的标准输出。

Open3.pipeline_rw(cmd1, cmd2, ... [, opts]) {|first_stdin, last_stdout, wait_threads|
  ...
}

first_stdin, last_stdout, wait_threads = Open3.pipeline_rw(cmd1, cmd2, ... [, opts])
...
first_stdin.close
last_stdout.close

每个 cmd 都是一个字符串或一个数组。如果它是一个数组,则将元素传递给 Process.spawn

cmd:
  commandline                              command line string which is passed to a shell
  [env, commandline, opts]                 command line string which is passed to a shell
  [env, cmdname, arg1, ..., opts]          command name and one or more arguments (no shell)
  [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)

Note that env and opts are optional, as for Process.spawn.

传递给 Process.spawn 的选项是通过合并数组的最后一个哈希元素 opts 以及每个命令之间的管道规范来构造的。

例子:

Open3.pipeline_rw("tr -dc A-Za-z", "wc -c") {|i, o, ts|
  i.puts "All persons more than a mile high to leave the court."
  i.close
  p o.gets #=> "42\n"
}

Open3.pipeline_rw("sort", "cat -n") {|stdin, stdout, wait_thrs|
  stdin.puts "foo"
  stdin.puts "bar"
  stdin.puts "baz"
  stdin.close     # send EOF to sort.
  p stdout.read   #=> "     1\tbar\n     2\tbaz\n     3\tfoo\n"
}

相关用法


注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Open3.pipeline_rw。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。