C# WPF 进程获取 StandardOutput 是间歇性的

C# WPF Process getting StandardOutput is intermittent

我的 WPF C# 文件中有一个 Python 进程 运行ning:

        ProcessStartInfo StartInfo = new ProcessStartInfo(@"python ", location);
        StartInfo.UseShellExecute = false;
        StartInfo.CreateNoWindow = true;
        StartInfo.RedirectStandardOutput = true;
        StartInfo.RedirectStandardError = true;
        try
        {
            p.StartInfo = StartInfo;
            p.EnableRaisingEvents = true;
            p.OutputDataReceived += new DataReceivedEventHandler(OnDataReceived);
            p.ErrorDataReceived += new DataReceivedEventHandler(OnDataReceived);
            p.Exited += new EventHandler(OnProcessExit);
            p.Start();
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
         }
        catch (Exception exc)
        {
            Console.Write(exc);
        }

及以后:

private void OnDataReceived(object sender, DataReceivedEventArgs e)
    {
        if (e.Data != null)
        {
            torOut = e.Data;
            Console.WriteLine(torOut);
        }
    }

我的 Python 程序每秒打印多条消息。当我 运行 这个时,只有部分输出出现;例如,print "message"可能会被调用50次,只有在第50次之后才会将所有50条消息作为一个批次出现。

是我的方法有问题,还是读取 StandardOutput 的速度特别慢/断断续续?

如果有人有类似的问题,我最终解决了。在需要任何时间输出后添加以下内容:

import sys
sys.stdout.flush()