获取系统调用的错误输出?

时间:2012-01-28 09:30:12

标签: ruby bash system

当我做以下事情时:

output = `identify some_file`
output == "Output of identify"

但是什么时候......

output = `identify non_existant_file`
output != "Error output of identify"

如何获取系统调用的错误输出?

2 个答案:

答案 0 :(得分:5)

我找到了答案。输出正被发送到stderr。所以我可以在命令末尾添加以下内容,将stderr重定向到stdout:

output = `identify any_file 2>&1`
output == "Error or output of identify"

Here is the explanation of this witchcraft

答案 1 :(得分:2)

您可以使用Open3.popen3

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/open3/rdoc/Open3.html#method-c-popen3

  

popen3(* cmd,& block)点击以切换来源

     

打开stdin,stdout和stderr流并启动外部可执行文件。

Open3.popen3([env,] cmd... [, opts]) {|stdin, stdout, stderr, wait_thr|
  pid = wait_thr.pid # pid of the started process.
  ...
  exit_status = wait_thr.value # Process::Status object returned.
}