gpt4 book ai didi

c# - 我正在尝试使用以下代码片段在 C# 中运行 R 脚本。但是输出会重复

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:20 25 4
gpt4 key购买 nike

      Process cmdProcess = new Process
{
StartInfo =
{
FileName = "cmd.exe",
WorkingDirectory = "C:/Program Files/R/R-3.0.2/bin",
Arguments = " /C R --slave --args $@ ",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
CreateNoWindow = true,
}
};

cmdProcess.Start();
cmdProcess.BeginOutputReadLine();

foreach (var item in File.ReadAllLines(“Audit.R”))
{
cmdProcess.StandardInput.WriteLine(item);
cmdProcess.OutputDataReceived += cmdProcess_OutputDataReceived;

}

}

然后我尝试使用以下事件获取输出。

    public void cmdProcess_OutputDataReceived(object sender,DataReceivedEventArgs e)
{
this.ResultText += e.Data + "\n";
}

我得到了重复的输出。这是我的输入 R 脚本,

getwd()
data<-read.csv("Audit.csv")
str(data)

谁能帮我解决这个问题?谢谢

最佳答案

看起来您正在多次添加 outputdatareceived 事件处理程序(导致每个事件多次调用)。我可能会把它重写成这样,但你可以用下面的 R 文件 IO 代替我的硬编码字符串:

    public class TestRProcess
{
public StringBuilder output = new StringBuilder();
public StringBuilder error = new StringBuilder();

string script =
@"getwd()
a<-1:3
b<-4:6
data<-data.frame(a,b)
str(data)
q()
";

public void Process()
{
ProcessStartInfo ProcessParameters = new ProcessStartInfo(@"C:\Program Files\R\R-3.1.1\bin\R.exe")
{
Arguments = "--vanilla --slave",
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true
};

int Max_Time = 10000;


Process p = new Process();
p.StartInfo = ProcessParameters;

//Borrowed: http://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why
output = new StringBuilder();
error = new StringBuilder();

using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
p.OutputDataReceived += (sender, e) =>
{
if (e.Data == null)
{
outputWaitHandle.Set();
}
else
{
output.AppendLine(e.Data);
}
};
p.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null)
{
errorWaitHandle.Set();
}
else
{
error.AppendLine(e.Data);
}
};

p.Start();

p.StandardInput.WriteLine(script);

p.BeginOutputReadLine();
p.BeginErrorReadLine();

if (p.WaitForExit(Max_Time) &&
outputWaitHandle.WaitOne(Max_Time) &&
errorWaitHandle.WaitOne(Max_Time))
{

}
else
{
throw new Exception("Timed Out");
}
}
}

关于c# - 我正在尝试使用以下代码片段在 C# 中运行 R 脚本。但是输出会重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25967558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com