从 Ruby 运行命令显示并捕获输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10224481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:02:23  来源:igfitidea点击:

Running a command from Ruby displaying and capturing the output

ruby

提问by pupeno

Is there some way to run a (shell) command from Ruby displaying but also capturing the output? Maybe with the help of some gem?

有没有办法从 Ruby 显示运行(shell)命令并捕获输出?也许在一些宝石的帮助下?

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.

我的意思是显示不是在最后打印它,而是在它出现时,所以用户在运行慢命令时会得到正在发生的事情的反馈。

回答by fl00r

You can run system call like this:

您可以像这样运行系统调用:

`sleep --help`

Or like this

或者像这样

system "sleep --help"

Or

或者

%x{ sleep --help }

In case of systemit will print output and return trueor nil, other two methods will return output

如果system它会打印输出并返回trueor nil,其他两种方法将返回输出

PSOh. It is about displaying in real time.

PS哦。这是关于实时显示。

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']

Or use popen

或使用 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']

回答by 0x4a6f4672

You can redirect the output

您可以重定向输出

system 'uptime > results.log'

or save the results.

或保存结果。

result = `uptime`
result = %x[uptime]

see here. Getting progress information or output in realtimeis more complicated, I doubt that there is a simple solution. Maybe it is possible with advanced process management functionssuch as Open3.popen3. You could also try to use a pseudo terminal with ptyand grap the output there.

看到这里实时获取进度信息或输出比较复杂,我怀疑是否有简单的解决方案。也许可以使用高级进程管理功能,例如Open3.popen3。你也可以尝试使用与PTY伪终端虎视眈眈的输出存在

回答by Kannan S

I used open3to captured the output of executed shell command from ruby code.

我曾经open3从 ruby​​ 代码中捕获执行的 shell 命令的输出。

require 'open3'

stdout, stdeerr, status = Open3.capture3("ls")

puts stdout

回答by jayhendren

If you are willing to explore a solution outside the standard library, you may also use Mixlib::ShellOutto both stream output and capture it:

如果您愿意探索标准库之外的解决方案,您还可以使用Mixlib::ShellOut流输出和捕获它:

require 'mixlib/shellout'
cmd = 'while true; do date; sleep 2; done'
so = Mixlib::ShellOut.new(cmd)
so.live_stream = $stdout
so.run_command
out = so.stdout