使用 DLR API 从 IronRuby 脚本捕获标准输出
我有一个非常简单的 test.rb 文件:
puts "Hello World"
我想在 c# 中执行这个文件,例如:
var runtime = Ruby.CreateRuntime();
runtime.ExecuteFile("C:\test.rb");
如何捕获“Hello World”?
I have a very simple test.rb file:
puts "Hello World"
I want to execute this file within c#, eg:
var runtime = Ruby.CreateRuntime();
runtime.ExecuteFile("C:\test.rb");
How can I capture the "Hello World"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
ScriptRuntime 有一个 IO 属性,它返回一个 ScriptIO 对象。您可以对其调用 SetOutput 并重定向输出。正如其他人提到的,还有 Console.SetOut,您可能希望在用户直接调用 Console.WriteLine 时调用它。使用 ScriptIO 的好处是,您可以在不同的 ScriptRuntime 中将多个脚本写入不同的输出。
ScriptRuntime has an IO property which returns a ScriptIO object. You can call SetOutput on that and redirect the output. As others have mentioned there's also Console.SetOut which you might want to call incase the user calls Console.WriteLine directly. The nice thing about using ScriptIO though is you can have multiple scripts in different ScriptRuntime's writing to different outputs.
您可以重定向标准输出并在 C# 程序中读取它如下所示< /a>.
You can redirect standard output and read it in your C# program as shown here.
您可以做的一件事是在 ExecuteFile 之前调用 Console.setOut 和/或 Console.setErr,然后再调用 Console.setErr。第一次,您会将输出重定向到您选择的流,然后将其恢复为之前的值。
One thing you can do is to call Console.setOut and/or Console.setErr before the ExecuteFile and again afterward. The first time you will redirect the output to a stream of your choosing, and then restore it to the previous value.
我认为这篇文章回答了您的问题。
I think that this post answers your question.