當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Ruby Open3.pipeline用法及代碼示例


本文簡要介紹ruby語言中 Open3.pipeline 的用法。

用法

pipeline(*cmds)

Open3.pipeline 將命令列表作為管道啟動。它等待命令的完成。沒有為第一個命令的標準輸入和最後一個命令的標準輸出創建管道。

status_list = Open3.pipeline(cmd1, cmd2, ... [, opts])

每個 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 Process.spawn.

例子:

fname = "/usr/share/man/man1/ruby.1.gz"
p Open3.pipeline(["zcat", fname], "nroff -man", "less")
#=> [#<Process::Status: pid 11817 exit 0>,
#    #<Process::Status: pid 11820 exit 0>,
#    #<Process::Status: pid 11828 exit 0>]

fname = "/usr/share/man/man1/ls.1.gz"
Open3.pipeline(["zcat", fname], "nroff -man", "colcrt")

# convert PDF to PS and send to a printer by lpr
pdf_file = "paper.pdf"
printer = "printer-name"
Open3.pipeline(["pdftops", pdf_file, "-"],
               ["lpr", "-P#{printer}"])

# count lines
Open3.pipeline("sort", "uniq -c", :in=>"names.txt", :out=>"count")

# cyclic pipeline
r,w = IO.pipe
w.print "ibase=14\n10\n"
Open3.pipeline("bc", "tee /dev/tty", :in=>r, :out=>w)
#=> 14
#   18
#   22
#   30
#   42
#   58
#   78
#   106
#   202

相關用法


注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Open3.pipeline。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。