何时使用在 Ruby 中启动子进程的每种方法 [英] When to use each method of launching a subprocess in Ruby

查看:29
本文介绍了何时使用在 Ruby 中启动子进程的每种方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 在 parse.y 中定义,参见 讨论
  • 分叉到管道
  • 需要'open3'
  • stdlib Open3
  • 需要'pty'
  • stdlib PTY
  • 需要'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.

推荐答案

  1. 当您想在变量中轻松捕获程序的输出时,请使用反引号.您可能只想将它用于短期运行的程序,因为这会阻塞.

  1. 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 在两种不同的情况下很方便:

system is convenient in two different cases:

一个.您有一个长时间运行的程序,并且希望在运行时打印输出(例如 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.system 可以像 exec 一样绕过 shell 扩展(比较 system "echo *"system "echo", "*")

b. system can bypass the shell expansion like exec (compare the output of system "echo *" and system "echo", "*")

系统阻塞直到子进程退出.

system blocks until the subprocess has exited.

fork 也有几个不同的用例:

fork has a couple different use cases as well:

一个.您想在单独的进程中运行一些 ruby​​ 代码(例如 fork { .... }

a. You want to run some ruby code in a separate process (e.g. fork { .... }

b.你想运行一个子进程(或不同的程序)而不阻塞你的脚本 fork { exec "bash" }.

b. You want to run a child process (or different program) without blocking progress of your script fork { exec "bash" }.

fork 是你的朋友,如果你想守护你的程序.

fork is your friend if you want to daemonize your program.

IO.popen 很有用.请注意,它不会捕获标准错误,因此如果您关心它,您需要使用 2>&1 重定向它.

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 为您提供一个单独的标准错误文件描述符(当您需要从标准输出中单独捕获时)

popen3 gives you a separate file descriptor for standard error (for when you need to capture that separately from standard out)

PTY.spawn 当您希望生成的程序表现得像从终端运行时是必需的.查看使用 systemPTY.spawn

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆