0

我有一些启动进程“python.exe”的代码,如果我设置 process.StartInfo.RedirectStandardInput=false,重定向输出将从进程返回流,输出可用并由 readOut() 或 readErr() 线程处理程序处理。但是,如果我将其设置为 true,我将不会从该过程中获得任何输出。我需要输入重定向,以便可以从 Windows 表单向进程发送输入。

我确实有 2 个线程,一个处理重定向的输出,另一个处理重定向的 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);
        }
    }           
4

2 回答 2

0

确保等到 p 完成,使用

p.WaitForExit();

您的示例中似乎缺少这一点。据我所知,其余部分是正确的,尽管也许可以写得更好:正如所写的那样,看起来如果没有可用的输出,您的代码就会旋转,等待。这将不必要地烧毁CPU。相反,只需继续调用 Read: 它将阻塞直到足够多,因此这将为其他线程或进程释放 CPU。

于 2013-06-18T01:33:09.550 回答
0

我已经弄清楚了问题所在。“p.StartInfo.RedirectStandardInput = true”工作正常。问题出在 Python.exe 中。我必须对 StartInfo.Arguments 使用“-i”arg 选项。它解释在

将 Python 标准输入/输出重定向到 C# 表单应用程序

于 2013-06-19T18:57:19.160 回答