使用 DLR API 从 IronRuby 脚本捕获标准输出

发布于 2024-08-24 21:15:54 字数 224 浏览 2 评论 0原文

我有一个非常简单的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

丑疤怪 2024-08-31 21:15:54

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.

硪扪都還晓 2024-08-31 21:15:54

您可以重定向标准输出并在 C# 程序中读取它如下所示< /a>.

You can redirect standard output and read it in your C# program as shown here.

ぺ禁宫浮华殁 2024-08-31 21:15:54

您可以做的一件事是在 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.

情绪少女 2024-08-31 21:15:54

我认为这篇文章回答了您的问题。

I think that this post answers your question.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文