2014-09-26 23 views
0

我想建立一个C程序,需要通过标准输入/输出流与R(rscript.exe)进行通信。但是我找不到在rscript的输入流中写入任何内容的方法。有没有办法使用标准的输入/输出流来交流C#和R?

这是C#程序,它使用一个进程的流被重定向。

using System; 
using System.Collections.Generic; 
using System.Diagnostics; 

namespace test1 
{ 
    class Program 
    {   
     static void Main(string[] args) 
     { 
      var proc = new Process(); 
      proc.StartInfo = new ProcessStartInfo("rscript", "script.R") 
      { 
       RedirectStandardInput = true, 
       RedirectStandardOutput = true, 
       UseShellExecute = false 
      }; 

      proc.Start();    

      var str = proc.StandardOutput.ReadLine(); 

      proc.StandardInput.WriteLine("hello2"); 

      var str2 = proc.StandardOutput.ReadToEnd(); 

     } 
    } 
} 

这里是script.R

cat("hello\n") 

input <- readline() 

cat("input is:",input, "\n") 

str能够捕捉到"hello""hello2"不能写为R的流,使得str2总是得到"\r\ninput is: \r\n"

有没有办法用这种方式将文本写入R的输入流?

+0

这可能是http://stackoverflow.com/q/9871307/602276 – Andrie 2014-09-26 06:57:38

+0

的副本,一个为什么要这么做?使用[R.NET](https://rdotnet.codeplex.com/),C#和其他.net方言和R之间存在非常好的接口。不仅可以轻松地交换字符串和标量,还可以交换矢量,矩阵,列表,...看看这个伟大的工作,并获得乐趣:-) – 2014-09-26 08:49:15

+0

感谢@PatrickRoocks,我故意避免在这种情况下使用R.NET由于某种原因,只是想知道一个最小的情况下与一个R会话通过stdio,我想我已经解决了这个问题。不管怎么说,还是要谢谢你! – 2014-09-26 08:57:21

回答

1

https://stackoverflow.com/a/9370949/2906900的答案适用于此问题。

以下是C#和rscript.exe通过stdio进行交互的最小示例。

在R脚本中,stdin连接必须明确打开。

R代码里面:

f <- file("stdin") 
open(f) 
input <- readLines(f, n = 1L) 
cat("input is:", input) 

在这种情况下,RSCRIPT的输入流可以被访问。

C#代码:

using System; 
using System.Collections.Generic; 
using System.Diagnostics; 

namespace test1 
{ 
    class Program 
    {   
     static void Main(string[] args) 
     { 
      var proc = new Process(); 
      proc.StartInfo = new ProcessStartInfo("rscript") 
      { 
       Arguments = "script.R", 
       RedirectStandardInput = true, 
       RedirectStandardOutput = true, 
       RedirectStandardError = true, 
       UseShellExecute = false 
      }; 

      proc.Start(); 
      proc.StandardInput.WriteLine("Hello"); 
      var output = proc.StandardOutput.ReadLine(); 
      Console.WriteLine(output); 
     } 
    } 
} 
相关问题