如果我调用一个命令使用内核#系统在Ruby中,我如何得到它的输出?
system("ls")
如果我调用一个命令使用内核#系统在Ruby中,我如何得到它的输出?
system("ls")
当前回答
只是为了记录,如果你想要(输出和操作结果),你可以这样做:
output=`ls no_existing_file` ; result=$?.success?
其他回答
你可以用反勾号:
`ls`
我发现下面是有用的,如果你需要返回值:
result = %x[ls]
puts result
我特别想列出我的机器上所有Java进程的pid,并使用以下方法:
ids = %x[ps ax | grep java | awk '{ print $1 }' | xargs]
你可以使用一个叫做Frontkick的宝石
Frontkick.exec("echo *")
下面是如何检查和阅读它:
result = Frontkick.exec("echo *")
puts result.successful? #=> true if exit_code is 0
puts result.success? #=> alias to successful?, for compatibility with Process::Status
puts result.stdout #=> stdout output of the command
puts result.stderr #=> stderr output of the command
puts result.exit_code #=> exit_code of the command
puts result.status #=> alias to exit_code
puts result.exitstatus #=> alias to exit_code, for compatibility with Process::Status
puts result.duration #=> the time used to execute the command
Github https://github.com/sonots/frontkick frontkick
创业板页面https://rubygems.org/gems/frontkick
puts `date`
puts $?
Mon Mar 7 19:01:15 PST 2016
pid 13093 exit 0
作为直接系统(…)替代品,您可以使用Open3.popen3(…)
进一步讨论: http://tech.natemurray.com/2007/03/ruby-shell-commands.html