何时使用每种方法在Ruby中启动子进程 [英] When to use each method of launching a subprocess in Ruby
问题描述
- ://www.ruby-doc.org/core/classes/Kernel.src/M001408.html>内核
的替代语法,请参阅讨论
- 打开管道 li>
- 内核#打开
- open a pipe
- Kernel#open
- 打开管道
- IO#popen
- / strong>
- 请参阅讨论
- fork to a pipe
- see discussion
-
require'open3'
- stdlib Open3
require 'open3'
- stdlib Open3
-
require'pty'
- stdlib PTY
require 'pty'
- stdlib PTY
-
- stdlib Shell
require 'shell'
- stdlib Shell
编辑1。
非常感谢 Avdi Grimm ,描述每种方法的示例用法:#1 (& gist ); # 2 (& gist ); #3 。
Edit 1. Big thanks to Avdi Grimm for his posts describing example usage of each method: #1 (& gist); #2 (& gist); #3.
他们是回答如何的奇妙资源,但没有明确构成回答或为什么 不完整的答案。
They are fantastic resources to answer How, but are not explicitly composed to answer when each should be used or Why, and as such IMHO are not complete answers to this question.
推荐答案
-
一个程序在一个变量中的输出。
use backticks when you want to easily capture the output of a program in a variable. you probably only want to use this for short-running programs, because this will block.
系统
您可能只想将其用于短期运行的程序,在两种不同的情况下很方便:
system
is convenient in two different cases:
a。你有一个长时间运行的程序,你希望输出打印,因为它运行(例如 system(tar zxvf some_big_tarball.tar.gz)
)
a. You have a long running program and you want the output to print as it runs (e.g. system("tar zxvf some_big_tarball.tar.gz")
)
b。 可以绕过shell扩展,如
exec
(比较系统的输出echo *
和系统echo,*
)
已退出。
fork
也有几个不同的用例:
fork
has a couple different use cases as well:
a。您要在单独的进程中运行一些ruby代码(例如 fork {....}
a. You want to run some ruby code in a separate process (e.g. fork { .... }
b。你想运行一个子进程(或不同的程序),而不阻塞你的脚本的进度 fork {execbash}
。
b. You want to run a child process (or different program) without blocking progress of your script fork { exec "bash" }
.
<$ c>
$ c> IO.popen
在需要与程序的标准输出和标准交互时非常有用。请注意,它不捕获标准错误,因此您需要使用<$
IO.popen
is useful when you need to interact with the standard out and standard in of a program. Note that it doesn't capture standard err, so you need to redirect that with 2>&1
if you care about that.
popen3 $>
当你希望生成的程序像从终端运行一样运行时,需要使用PTY.spawn
。见 grep --color = auto pat file
与系统
vs 产生时
PTY.spawn
is necessary when you want the spawned program to behave like you are running from the terminal. See the difference of grep --color=auto pat file
when spawned with system
vs PTY.spawn
这篇关于何时使用每种方法在Ruby中启动子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!