puts "hi"
puts "bye"
我想存储到目前为止代码的 STDOUT(在本例中嗨 再见变量,说“结果”并打印它)
puts result
我这样做的原因是我将 R 代码集成到我的 Ruby 代码中,当 R 代码运行时,其输出被提供给 STDOUT,但无法在代码内部访问输出以进行某些评估。抱歉,如果这令人困惑。所以“puts result”行应该给我打招呼和再见。
以下方法是一个方便的通用工具,用于捕获标准输出并将其作为字符串返回。 (我在单元测试中经常使用它,我想验证打印到标准输出的内容。)特别注意使用
ensure
子句来恢复 $stdout (并避免惊讶):
def with_captured_stdout
original_stdout = $stdout # capture previous value of $stdout
$stdout = StringIO.new # assign a string buffer to $stdout
yield # perform the body of the user code
$stdout.string # return the contents of the string buffer
ensure
$stdout = original_stdout # restore $stdout to its previous value
end
所以,例如:
>> str = with_captured_stdout { puts "hi"; puts "bye"}
=> "hi\nbye\n"
>> print str
hi
bye
=> nil
您当然可以将标准输出重定向到变量。例如:
# Set up standard output as a StringIO object.
foo = StringIO.new
$stdout = foo
# Send some text to $stdout.
puts 'hi'
puts 'bye'
# Access the data written to standard output.
$stdout.string
# => "hi\nbye\n"
# Send your captured output to the original output stream.
STDOUT.puts $stdout.string
实际上,这可能不是一个好主意,但至少现在您知道这是可能的。
如果您的项目提供主动支持,您可以执行以下操作:
output = capture(:stdout) do
run_arbitrary_code
end
有关
Kernel.capture
的更多信息可以在这里找到
您可以通过在反引号内调用 R 脚本来完成此操作,如下所示:
result = `./run-your-script`
puts result # will contain STDOUT from run-your-script
有关在 Ruby 中运行子进程的更多信息,请查看这个 Stack Overflow 问题。
# capture_stream(stream) { block } -> String
#
# Captures output on +stream+ for both Ruby code and subprocesses
#
# === Example
#
# capture_stream($stdout) { puts 1; system("echo 2") }
#
# produces
#
# "1\n2\n"
#
def capture_stream(stream)
raise ArgumentError, 'missing block' unless block_given?
orig_stream = stream.dup
IO.pipe do |r, w|
# system call dup2() replaces the file descriptor
stream.reopen(w)
# there must be only one write end of the pipe;
# otherwise the read end does not get an EOF
# by the final `reopen`
w.close
t = Thread.new { r.read }
begin
yield
ensure
stream.reopen orig_stream # restore file descriptor
end
t.value # join and get the result of the thread
end
end
我从Zhon得到了灵感。
对于大多数实际用途,您可以将任何内容放入
$stdout
中,以响应 write
、flush
、sync
、sync=
和 tty?
。
在此示例中,我使用了 stdlib 中经过修改的 Queue。
class Captor < Queue
alias_method :write, :push
def method_missing(meth, *args)
false
end
def respond_to_missing?(*args)
true
end
end
stream = Captor.new
orig_stdout = $stdout
$stdout = stream
puts_thread = Thread.new do
loop do
puts Time.now
sleep 0.5
end
end
5.times do
STDOUT.print ">> #{stream.shift}"
end
puts_thread.kill
$stdout = orig_stdout
如果您想主动对数据采取行动,而不仅仅是在任务完成后查看数据,则需要这样的东西。使用 StringIO 或文件将会有多个线程尝试同时同步读取和写入的问题。
Minitest
版本:
assert_output
如果您需要确保是否生成一些输出:
assert_output "Registrars processed: 1\n" do
puts 'Registrars processed: 1'
end
或者如果您确实需要捕获它,请使用
capture_io
:
out, err = capture_io do
puts "Some info"
warn "You did a bad thing"
end
assert_match %r%info%, out
assert_match %r%bad%, err
Minitest
本身可用于从 1.9.3
开始的任何 Ruby 版本
对于 RinRuby,请知道 R 有
capture.output
:
R.eval <<EOF
captured <- capture.output( ... )
EOF
puts R.captured
感谢@girasquid 的回答。我修改为单文件版本:
def capture_output(string)
`echo #{string.inspect}`.chomp
end
# example usage
response_body = "https:\\x2F\\x2Faccounts.google.com\\x2Faccounts"
puts response_body #=> https:\x2F\x2Faccounts.google.com\x2Faccounts
capture_output(response_body) #=> https://accounts.google.com/accounts