在Ruby中获取system()调用的输出 [英] Getting output of system() calls in Ruby

查看:148
本文介绍了在Ruby中获取system()调用的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用内核#system 在Ruby中,如何获取其输出?

If I call a command using Kernel#system in Ruby, how do I get its output?

system("ls")


推荐答案

我想扩展&澄清一下混乱的答案

I'd like to expand & clarify chaos's answer a bit.

如果包围命令使用反引号,则根本不需要(明确地)调用system()。反引号执行命令并以字符串形式返回输出。然后,您可以将值分配给变量,如下所示:

If you surround your command with backticks, then you don't need to (explicitly) call system() at all. The backticks execute the command and return the output as a string. You can then assign the value to a variable like so:

output = `ls`
p output

printf output # escapes newline chars

这篇关于在Ruby中获取system()调用的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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