Running a shell command from Ruby: capturing the output while displaying the output?

后端 未结 7 1444

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

7条回答
  •  情书的邮戳
    2021-02-10 02:55

    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

提交回复
热议问题