2014-09-26 26 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); 
     } 
    } 
} 
相關問題