首页 > 解决方案 > 如何在 C# 中捕获 Python 脚本的输出,因为它在运行时打印文本?

问题描述

我有以下 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
                { }
        }

我不确定为什么在脚本运行时没有调用ProcessOutputHandler。我怎么能得到那个输出?(实时来自 Python 脚本的数字)

标签: c#pythonprocessstartinfo

解决方案


推荐阅读