C#Process.StartInfo.RedirectStandardInput=true不返回重定向的输出或错误
我有一些启动进程“python.exe”的代码,如果我设置process.StartInfo.RedirectStandardInput=false,重定向的输出将从进程返回流,输出可用并由readOut()或readErr()线程处理程序处理。然而,如果我将其设置为true,我将无法从流程中获得任何输出。我需要输入重定向,以便可以从Windows窗体向进程发送输入 我有两个线程,一个处理重定向的输出,另一个处理重定向的stderror。如果你能提供一些建议,我将不胜感激。多谢各位 我的代码是这样的:C#Process.StartInfo.RedirectStandardInput=true不返回重定向的输出或错误,c#,stdio,io-redirection,C#,Stdio,Io Redirection,我有一些启动进程“python.exe”的代码,如果我设置process.StartInfo.RedirectStandardInput=false,重定向的输出将从进程返回流,输出可用并由readOut()或readErr()线程处理程序处理。然而,如果我将其设置为true,我将无法从流程中获得任何输出。我需要输入重定向,以便可以从Windows窗体向进程发送输入 我有两个线程,一个处理重定向的输出,另一个处理重定向的stderror。如果你能提供一些建议,我将不胜感激。多谢各位 我的代码是这
....
Process p = new Process();
p.StartInfo.WorkingDirectory = "C:\\";
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
//output is available and processed by readErr if this set to false.
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.EnableRaisingEvents = true;
p.StartInfo.FileName = this.exe;
readTh = new Thread(readOut);
readTh.Name = "CmdStdOutTh";
errTh = new Thread(readErr);
errTh.Name = "CmdStdErrTh";
lock (this)
{
p.Start();
readTh.Start();
errTh.Start();
}
....
void readOut()
{
char[] buf = new char[256];
int n = 0;
while ((!p.HasExited || (p.StandardOutput.Peek() >= 0)) && !abort) {
n = p.StandardOutput.Read(buf, 0, buf.Length - 1);
buf[n] = '\0';
if (n > 0)
processOutput(new string(buf));
Thread.Sleep(0);
}
}
void readErr() {
char[] buf = new char[256];
while ((!p.HasExited || (p.StandardError.Peek() >= 0)) && !abort) {
int n = p.StandardError.Read(buf, 0, buf.Length - 1);
buf[n] = '\0';
if (n > 0)
processError(new string(buf));
Thread.Sleep(0);
}
}
确保等待p完成,使用
p.WaitForExit();
你的例子中似乎没有这一点。就我所知,其余部分是正确的,尽管可能编写得更好:在编写时,如果没有可用的输出,您的代码就会旋转,等待。这将不必要地消耗CPU。相反,只需继续调用Read:它将阻塞,直到有足够的内存,因此这将释放其他线程或进程的CPU。我已经解决了这个问题。“p.StartInfo.RedirectStandardInput=true”工作正常。问题出在Python.exe中。我必须对StartInfo.Arguments使用“-I”arg选项。这一点在本书中有解释 我的代码中有p.WaitForExit(),这里不包括它。回到最初的问题,上面代码的问题是,如果我的RedirectStandardOutput=true,我就无法从可执行文件(Python.exe)获取输出。如果将其设置为false,则可以正常工作。我将在readErr()的buf上返回Python横幅,其内容为“win32上的Python 2.7.5(默认值,2013年5月15日,22:43:36)[MSC v.1500 32位(英特尔)]。为什么管子里什么都没有?我有两个线程在这里为它服务,因为位在读和错误IO时进入。