从 Ruby 运行命令显示并捕获输出 [英] Running a command from Ruby displaying and capturing the output
问题描述
有什么方法可以从 Ruby 显示运行(shell)命令并捕获输出?也许在一些宝石的帮助下?
Is there some way to run a (shell) command from Ruby displaying but also capturing the output? Maybe with the help of some gem?
我所说的显示不是在最后打印它,而是当它出现时,所以用户在运行缓慢的命令时会得到正在发生的事情的反馈.
What I mean by displaying is not printing it at the end, but as it appears, so the user gets the feedback of what's going on when running slow commands.
推荐答案
你可以像这样运行系统调用:
You can run system call like this:
`sleep --help`
或者像这样
system "sleep --help"
或
%x{ sleep --help }
在system
的情况下,它会打印输出并返回true
或nil
,其他两种方法将返回输出
In case of system
it will print output and return true
or nil
, other two methods will return output
PS 哦.这是关于实时显示.
PS Oh. It is about displaying in real time.
所以.你可以使用这样的东西:
So. You could use something like this:
system("ruby", "-e 100.times{|i| p i; sleep 1}", out: $stdout, err: :out)
要实时打印数据并将其存储在变量中:
To print data in realtime and store it in variable:
output = []
r, io = IO.pipe
fork do
system("ruby", "-e 3.times{|i| p i; sleep 1}", out: io, err: :out)
end
io.close
r.each_line{|l| puts l; output << l.chomp}
#=> 0
#=> 1
#=> 2
p output
#=> ['0', '1', '2']
或者使用popen
output = []
IO.popen("ruby -e '3.times{|i| p i; sleep 1}'").each do |line|
p line.chomp
output << line.chomp
end
#=> '0'
#=> '1'
#=> '2'
p output
#=> ['0', '1', '2']
这篇关于从 Ruby 运行命令显示并捕获输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!