gpt4 book ai didi

ruby - 从 Ruby : capturing the output while displaying the output? 运行 shell 命令

转载 作者:数据小太阳 更新时间:2023-10-29 07:12:27 24 4
gpt4 key购买 nike

我有一个问题。

我想从另一个 ruby​​ 脚本运行一个 ruby​​ 脚本并捕获它的输出信息,同时让它也输出到屏幕。

亚军

#!/usr/bin/env ruby
print "Enter your password: "
password = gets.chomp
puts "Here is your password: #{password}"

我运行的脚本文件:

开始.rb

output = `runner`
puts output.match(/Here is your (password: .*)/).captures[0].to_s

正如您在此处看到的那样,存在问题。

在 start.rb 的第一行,屏幕是空的。

我在运行程序中看不到“输入您的密码:”。

有没有办法在运行脚本完成之前显示它的输出,并且仍然让我将它捕获到一个字符串中以便我可以处理信息,例如。在这个例子中使用匹配?

最佳答案

运行者.rb

STDOUT.print "Enter your password: "
password = gets.chomp
puts "Here is your password: #{password}"

注意 STDOUT.print

开始.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

输出

Enter your password: hello
password: hello

阅读更多...

我最近在这里写了一篇文章:Output Buffering with Ruby

关于ruby - 从 Ruby : capturing the output while displaying the output? 运行 shell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3682837/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com