使用%x捕获命令行错误

只要您想在命令行上执行某些操作,就可以使用以下语法:

%x(command to run) 

但是,我想捕获错误或至少得到响应,以便我可以正确解析它。 我尝试过设置:

 result = %x(command to run) 

并使用try-catch

 begin %x(command to run) rescue "didn't work" end 

无济于事。 如何捕获结果而不是打印出来?

所以这并没有直接回答你的问题(不会捕获命令的输出)。 但是,您可以只检查命令的退出代码( $? ),而不是尝试begin / rescue

 %x(command to run) unless $? == 0 "ack! error occurred" end 

编辑 :刚想起这个新项目。 我认为它完全符合您的要求:

https://github.com/envato/safe_shell

您可能希望将stderr重定向到stdout

 result = %x(command to run 2>&1) 

或者,如果要将错误消息与实际输出分开,可以使用popen3:

 require 'open3' stdin, stdout, stderr = Open3.popen3("find /proc") 

然后,您可以从stdout读取实际输出,并从stderr读取错误消息。

你需要混合@Cam的答案和@tonttu的答案。

decent explanation of $? and others.

编辑:域名http://blog.purifyapp.com现在掌握在域名抢注者和诈骗者手中。

 result = %x(command to run 2>&1) unless $? == 0 #check if the child process exited cleanly. puts "got error #{result}" end 

以下是如何使用Ruby的open3:

 require 'open3' include Open3 stdin, stdout, stderr = popen3('date') stdin.close puts puts "Reading STDOUT" print stdout.read stdout.close puts puts "Reading STDERR" print stderr.read stderr.close # >> # >> Reading STDOUT # >> Sat Jan 22 20:03:13 MST 2011 # >> # >> Reading STDERR 

popen3为STDIN,STDOUT和STDERR返回IO流,允许您对打开的应用程序执行I / O操作。

许多命令行应用程序要求在处理输入之前关闭STDIN。

您必须从返回的STDOUT和STDERR管道中读取。 它们不会自动将内容推送到神秘变量中。

一般来说,我喜欢使用带有popen3的块,因为它可以处理自身后面的清理工作。

查看Open3文档中的示例。 有很多不错的function。