外部命令如何将其输出和退出状态返回给Ruby?

时间:2021-06-08 00:04:51

This is a follow up question regarding ruby system command check exit code. I want to run command such that to get its output as well as exit code. Currently what I used in the code is:

这是关于ruby系统命令检查退出代码的后续问题。我想运行命令,以获取其输出以及退出代码。目前我在代码中使用的是:

rv = `#{cmd} 2>&1`

But this only captures output, and

但这只能捕获输出,并且

rv = system(cmd)

only captures the exit code. How to achieve both?

仅捕获退出代码。如何实现两者?

3 个解决方案

#1


6  

Check $?.exitstatus for the exit code.

检查$ ?. exitstatus以获取退出代码。

For more info, see http://www.ruby-doc.org/core-2.1.0/Process/Status.html

有关详细信息,请参阅http://www.ruby-doc.org/core-2.1.0/Process/Status.html

#2


3  

Backticks will capture the output from your command. For example, to store the output in the rv variable:

反引号将捕获命令的输出。例如,要将输出存储在rv变量中:

rv = `echo Error: EX_USAGE; exit 64`
#=> "Error: EX_USAGE\n"

You can interrogate the exit status of the process from the built-in $? variable or from a Process::Status object. For example, to get the exit status of the last backtick command:

您可以从内置$查询进程的退出状态?变量或来自Process :: Status对象。例如,要获取最后一个反引号命令的退出状态:

$?.exitstatus
#=> 64

#3


1  

$? accesses the status of the last system executed command if you use the backticks, system() or %{}. You can then access the exitstatus and pid properties.

$?如果使用反引号,system()或%{},则访问上次系统执行命令的状态。然后,您可以访问exitstatus和pid属性。

Source

So you can do rv = system(cmd), and do status = $?.exitstatus.

所以你可以做rv = system(cmd),并做status = $ ?. exitstatus。

#1


6  

Check $?.exitstatus for the exit code.

检查$ ?. exitstatus以获取退出代码。

For more info, see http://www.ruby-doc.org/core-2.1.0/Process/Status.html

有关详细信息,请参阅http://www.ruby-doc.org/core-2.1.0/Process/Status.html

#2


3  

Backticks will capture the output from your command. For example, to store the output in the rv variable:

反引号将捕获命令的输出。例如,要将输出存储在rv变量中:

rv = `echo Error: EX_USAGE; exit 64`
#=> "Error: EX_USAGE\n"

You can interrogate the exit status of the process from the built-in $? variable or from a Process::Status object. For example, to get the exit status of the last backtick command:

您可以从内置$查询进程的退出状态?变量或来自Process :: Status对象。例如,要获取最后一个反引号命令的退出状态:

$?.exitstatus
#=> 64

#3


1  

$? accesses the status of the last system executed command if you use the backticks, system() or %{}. You can then access the exitstatus and pid properties.

$?如果使用反引号,system()或%{},则访问上次系统执行命令的状态。然后,您可以访问exitstatus和pid属性。

Source

So you can do rv = system(cmd), and do status = $?.exitstatus.

所以你可以做rv = system(cmd),并做status = $ ?. exitstatus。