在Ruby运行shell命令:捕获输出,同时显示输出? [英] Running a shell command from Ruby: capturing the output while displaying the output?
问题描述
我有一个问题。
我想从另一个Ruby脚本运行Ruby脚本,并捕获它的输出信息,同时输出让它在屏幕上了。
亚军
#!的/ usr / bin中/ env的红宝石
打印请输入密码
密码= gets.chomp
把这是你的密码:#{}密码
该脚本文件,我运行:
start.rb
输出=`runner`
把output.match(/这里是你的(密码:。*)/)捕捉[0] .to_s。
正如你看到这里有一个问题。
在start.rb的第一行的屏幕是空的。
我看不到输入您的密码:在亚军
有没有办法显示脚本亚军它完成之前的输出,并且还让我捕捉它为一个字符串,所以我可以处理信息,如一种方式。在这个例子中使用的比赛怎么样?
runner.rb
STDOUT.print输入您的密码:
密码= gets.chomp
把这是你的密码:#{}密码
注意 STDOUT.print
start.rb
规定StringIO的缓冲= StringIO.new
$标准输出=缓冲区要求亚军$标准输出= STDOUT
buffer.rewind把buffer.read.match(/这里是你的(密码:。*)/)捕捉[0] .to_s。
输出
输入您的密码:您好
密码:您好
阅读全文...
我最近做了这样一个在这里写了:用Ruby 输出缓冲一>
I have a problem.
I want to run a ruby script from another ruby script and capture it's output information while letting it output to the screen too.
runner
#!/usr/bin/env ruby
print "Enter your password: "
password = gets.chomp
puts "Here is your password: #{password}"
The script file that I run:
start.rb
output = `runner`
puts output.match(/Here is your (password: .*)/).captures[0].to_s
As you see here there is a problem.
In the first line of start.rb the screen is empty.
I cannot see the "Enter your password: " in runner.
Is there a way to display the output of the runner script before it's finished, and still let me capture it to a string so I can process the information, eg. using match like in this example?
runner.rb
STDOUT.print "Enter your password: "
password = gets.chomp
puts "Here is your password: #{password}"
Note STDOUT.print
start.rb
require "stringio"
buffer = StringIO.new
$stdout = buffer
require "runner"
$stdout = STDOUT
buffer.rewind
puts buffer.read.match(/Here is your (password: .*)/).captures[0].to_s
output
Enter your password: hello
password: hello
Read more...
I recently did a write-up on this here: Output Buffering with Ruby
这篇关于在Ruby运行shell命令:捕获输出,同时显示输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!