【问题标题】:Calling a ruby script from c#从 C# 调用 ruby​​ 脚本
【发布时间】:2021-02-05 20:52:54
【问题描述】:

这里回答calling a ruby script in c#

但这有效吗?我试过这个,但它一直失败并出现“系统找不到指定的文件”错误,我假设它是因为文件名之前的 ruby​​ 命令,但我不太确定。

感谢您的帮助

【问题讨论】:

  • 如果你安装了 ruby​​ 并且代码 ruby C:\ruby_script.rb 中的文件路径是正确的,它应该可以工作..

标签: c# .net ruby


【解决方案1】:

您也可以尝试使用 IronRuby 执行 Ruby 代码

using System;
using Microsoft.Scripting.Hosting;
using IronRuby;

class ExecuteRubyExample
{
    static void Main()
    {
        ScriptEngine engine = IronRuby.Ruby.CreateEngine();
        engine.ExecuteFile("C:/rubyscript.rb");
    }
}

【讨论】:

  • 我确实检查了 IR,但遗憾的是我仍在运行 3.5 并且不想从源代码编译 IR 代码,但是这是一个不错的选择,谢谢
【解决方案2】:

链接的答案看起来相当正确,但显然不适合您。这意味着它可能是两件事之一。

1) 反斜杠在咬你。尝试改变

ProcessStartInfo info = new ProcessStartInfo("ruby C:\rubyscript.rb");

ProcessStartInfo info = new ProcessStartInfo(@"ruby C:\rubyscript.rb");

ProcessStartInfo info = new ProcessStartInfo("ruby C:\\rubyscript.rb");

第一个更改使用字符串文字,第二个更改正确转义反斜杠。

2) 环境路径没有将 Ruby 的 bin 目录导出到它。这不太可能,而且测试起来更痛苦,所以我会专注于第一个。

【讨论】:

  • 不错的答案;但在第 2 点,最新版本的 Windows 为您提供了where 命令,这使得路径问题很容易解决。只需运行where ruby,您将获得路径中与模式匹配的内容列表。如果没有匹配项,您将收到错误消息。
  • @Iceman - 感谢where 命令的提示 - 我不知道。不幸的是,我在工作中被困在 WinXP 上,所以这对我没有好处。
  • 感谢大家的帮助,由于某种原因,示例中的编写方式对我不起作用,而我最终让它工作的方式就是这样做ProcessStartInfo rubyProc = new ProcessStartInfo(@"ruby"); rubyProc.Arguments = @"C:\rubytest.rb";
【解决方案3】:

这是我运行 ruby​​ 脚本的代码。

using (var proc = new Process())
{
    var startInfo = new ProcessStartInfo(@"ruby");
    startInfo.Arguments = filePath;
    startInfo.UseShellExecute = false;
    startInfo.CreateNoWindow = true;
    proc.StartInfo = startInfo;
    proc.Start();
}

这个方法运行它asynchronously,因为脚本可能需要未知的时间来运行这允许mainthread在不锁定它的情况下继续运行,然后等待脚本完成运行后再返回Task

private async Task RunRubyScript(string filePath)
{
  await Task.Run(() =>
  {
    using (var proc = new Process())
    {
      var startInfo = new ProcessStartInfo(@"ruby");
      startInfo.Arguments = filePath;
      startInfo.UseShellExecute = false;
      startInfo.CreateNoWindow = true;
      proc.StartInfo = startInfo;
      proc.Start();
      proc.WaitForExit();
    }
  });
}

希望这会有所帮助!

【讨论】:

    【解决方案4】:

    试试这个

    void runScript()
    {
        using (Process p = new Process())
        {
            ProcessStartInfo info = new ProcessStartInfo("ruby");
            info.Arguments = "C:\rubyscript.rb args"; // set args
            info.RedirectStandardInput = true;
            info.RedirectStandardOutput = true;
            info.UseShellExecute = false;
            p.StartInfo = info;
            p.Start();
            string output = p.StandardOutput.ReadToEnd();
            // process output
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-03
      • 1970-01-01
      • 2011-01-18
      • 1970-01-01
      • 1970-01-01
      • 2017-11-02
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      相关资源
      最近更新 更多