【发布时间】:2021-02-05 20:52:54
【问题描述】:
这里回答calling a ruby script in c#
但这有效吗?我试过这个,但它一直失败并出现“系统找不到指定的文件”错误,我假设它是因为文件名之前的 ruby 命令,但我不太确定。
感谢您的帮助
【问题讨论】:
-
如果你安装了 ruby 并且代码
ruby C:\ruby_script.rb中的文件路径是正确的,它应该可以工作..
这里回答calling a ruby script in c#
但这有效吗?我试过这个,但它一直失败并出现“系统找不到指定的文件”错误,我假设它是因为文件名之前的 ruby 命令,但我不太确定。
感谢您的帮助
【问题讨论】:
ruby C:\ruby_script.rb 中的文件路径是正确的,它应该可以工作..
您也可以尝试使用 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");
}
}
【讨论】:
链接的答案看起来相当正确,但显然不适合您。这意味着它可能是两件事之一。
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 目录导出到它。这不太可能,而且测试起来更痛苦,所以我会专注于第一个。
【讨论】:
where 命令,这使得路径问题很容易解决。只需运行where ruby,您将获得路径中与模式匹配的内容列表。如果没有匹配项,您将收到错误消息。
where 命令的提示 - 我不知道。不幸的是,我在工作中被困在 WinXP 上,所以这对我没有好处。
ProcessStartInfo rubyProc = new ProcessStartInfo(@"ruby"); rubyProc.Arguments = @"C:\rubytest.rb";
这是我运行 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();
}
});
}
希望这会有所帮助!
【讨论】:
试试这个
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
}
}
【讨论】: