在运行时打印文本时,如何捕获C#中Python脚本的输出?

时间:2019-01-10 15:17:21

标签: c# python processstartinfo

我有以下Python脚本:

import time
for x in range(10):
    print(x)
    time.sleep(0.05)

我想运行此脚本并在运行时捕获其输出。 我使用了以下C#代码,但直到完全完成循环后,它才显示任何数字。

        private void DoScriptTest()
        {
            ProcessStartInfo start = new ProcessStartInfo();
            string cmd = @"c:\flowers\count.py";
            start.FileName = @"C:\Users\pubud\AppData\Local\Programs\Python\Python36\python.exe";
            start.Arguments = string.Format("{0}", cmd);
            start.UseShellExecute = false;// Do not use OS shell
            start.CreateNoWindow = true; // We don't need new window
            start.RedirectStandardOutput = true;// Any output, generated by application will be redirected back
            start.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions)

            Process process = new Process();
            process.StartInfo = start;
            process.EnableRaisingEvents = true;
            process.OutputDataReceived += ProcessOutputHandler;
            process.Start();
            process.BeginErrorReadLine();
            process.BeginOutputReadLine();
            process.WaitForExit();
        }

        private void ProcessOutputHandler(object sender, DataReceivedEventArgs e)
    {
            if (!String.IsNullOrEmpty(e.Data))
                try {
                        TxtPrompt.Invoke((MethodInvoker)delegate {
                            TxtPrompt.AppendText(e.Data);
                            TxtPrompt.Refresh();
                        });
                    }
                    catch
                { }
        }

我不确定为什么在脚本运行时为何未调用?我如何获得该输出? (数字实时来自Python脚本)

0 个答案:

没有答案