Fork me on GitHub

C# 启动 Python 不能及时获取输出信息

结论:
在print函数前加上sys.stdout.flush()
有的说加在print之后,都可以试试。

from time import sleep
import sys

if __name__=="__main__":
    sys.stdout.flush()
    print("Start")
    for i in range(10000):
        # sys.stdout.write(str(i))
        sys.stdout.flush()
        print(i)
        sleep(0.5)
    print("End")

pass

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string pythonPath = @"C:\Users\vivi\AppData\Local\Programs\Python\Python310-32\python.exe";
            string pyFilePath = @"C:\Users\vivi\source\repos\WpfApp27\WpfApp27\bin\Debug\net6.0-windows\main.py";


            //调用python
            process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = pythonPath,
                    Arguments = $"{pyFilePath}",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true,
                },
                EnableRaisingEvents = true
            };

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            process.StartInfo.StandardOutputEncoding = Encoding.UTF8;
            process.StartInfo.StandardErrorEncoding = Encoding.UTF8;
            process.ErrorDataReceived += Process_ErrorDataReceived;
            process.OutputDataReceived += Process_OutputDataReceived;

            process.Exited += async (sender, args) =>
            {
                //立即销毁的话,可能有的消息收不到i
                await Task.Delay(5000);
                process.Dispose();


            };
            Task.Factory.StartNew(() =>
            {
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();
                Console.Read();
            });
        }

        private void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(e.Data))
                    return;

                Debug.WriteLine(e.Data);
            }
            catch (Exception err)
            {
                throw err;
            }
        }

        private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(e.Data))
                    return;

                Debug.WriteLine(e.Data);
            }
            catch (Exception err)
            {
                throw err;
            }
        }

posted @ 2024-03-11 16:04  猫叔Vincent  阅读(41)  评论(0编辑  收藏  举报