如何将 STDOUT 捕获到字符串? [英] How can I capture STDOUT to a string?

查看:47
本文介绍了如何将 STDOUT 捕获到字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

puts "hi"
puts "bye"

到目前为止,我想存储代码的 STDOUT(在这种情况下,hi \nbye 到一个变量中,例如result"并打印出来)

I want to store the STDOUT of the code so far (in this case hi \nbye into a variable say 'result' and print it )

puts result

我这样做的原因是我已将 R 代码集成到我的 Ruby 代码中,其输出在 R 代码运行时提供给 STDOUT,但无法在代码内部访问输出以进行一些评估.对不起,如果这令人困惑.所以puts result"行应该给我打招呼.

The reason I am doing this is I have integrate an R code into my Ruby code, output of which is given to the STDOUT as the R code runs , but the ouput cannot be accessed inside the code to do some evaluations. Sorry if this is confusing. So the "puts result" line should give me hi and bye.

推荐答案

将标准输出重定向到 StringIO 对象

您当然可以将标准输出重定向到变量.例如:

Redirect Standard Output to a StringIO Object

You can certainly redirect standard output to a variable. For example:

# 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

实际上,这可能不是一个好主意,但至少现在您知道这是可能的.

In practice, this is probably not a great idea, but at least now you know it's possible.

这篇关于如何将 STDOUT 捕获到字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆