【问题标题】:C# capturing python.exe output and displaying it in textboxC# 捕获 python.exe 输出并将其显示在文本框中
【发布时间】:2011-05-11 16:50:12
【问题描述】:

我已经在这个问题上工作了一段时间。我可以很好地捕获控制台窗口的输出(live),但我无法实时捕获python控制台应用程序的输出。我可以在 python 程序完成运行后捕获它的输出,但我不希望这样。 我正在使用 system.diagonistics 中的流程。与后台工作人员。 我只是想将 python26 输出捕获到文本框中。我已经用其他自定义应用程序测试了我的程序,它确实显示了输出(实时)。

请帮忙

谢谢

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using System.IO;

namespace ProcessDisplayoutput
{
public partial class Form1 : Form
{

    //Delegates

    delegate void AppendTextDelegate(string text);

    public Form1()
    {
        InitializeComponent();
        Worker.DoWork += new DoWorkEventHandler(Worker_DoWork);

    }

    private void StartButton_Click(object sender, EventArgs e)
    {
        ResultTextBox.Clear();
        if (!Worker.IsBusy)
        {
            Worker.RunWorkerAsync();
        }
    }

    public void Worker_DoWork(object sender, DoWorkEventArgs e)
    {
        Process pro = new Process();
        pro.StartInfo.RedirectStandardOutput = true;
        pro.StartInfo.RedirectStandardError = true;
        pro.StartInfo.UseShellExecute = false;
        pro.StartInfo.CreateNoWindow = true;
        pro.EnableRaisingEvents = true;
        pro.OutputDataReceived +=new DataReceivedEventHandler(OnDataReceived);
        pro.ErrorDataReceived +=new DataReceivedEventHandler(OnDataReceived);

        //Test with random program worked,
        //now need to test with python
        //*****************TEST 1: PASSED **************************
        pro.StartInfo.FileName = "C:\\TestProcessOutput.exe";
        //*****************END TEST1*******************************

        //*****************TEST 2: FAILED *************************
        //pro.StartInfo.FileName = "C:\\Python26\\python.exe";
        //pro.StartInfo.Arguments = "\"C:\\Python26\\testScript.py\"";
        //*****************END TEST2 *******************************

        StreamReader sr = null;
        try
        {
            pro.Start();

            pro.BeginOutputReadLine();
            //An alternative option to display the output with the same results
            //sr = pro.StandardOutput;
            //string line = "";
            //while ((line = sr.ReadLine()) != null)
            //{
           //     appendText(line);
           // }

        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }


    public void OnDataReceived(object sender, DataReceivedEventArgs e)
    {

        if (e.Data != null)
        {
            string temp = (e.Data) + Environment.NewLine;
            appendText(temp);

        }
    }
    public void appendText(string text)
    {
        if (ResultTextBox.InvokeRequired)
        {
            ResultTextBox.Invoke(new AppendTextDelegate(appendText), new object[] { text });
        }
        else
        {
            ResultTextBox.AppendText(text);
        }
    }

【问题讨论】:

  • 您是否尝试过轮询输出流而不是使用该事件并查看您是否正在获取任何数据。文档每次收到一行时都会调用该事件,但是我想知道这是否意味着 \c\n 或只是 \n
  • Ironpython 文本框可能是一个有用的工具 codeproject.com/KB/miscctrl/irontextbox.aspx
  • 你有没有想过这个问题?

标签: c# python process capture-output


【解决方案1】:

我自己也遇到了这个问题,经过大量试验后,对我有用的是使用“-u”选项运行 python 进程,这使得输出无缓冲。有了这个,一切都很好。

【讨论】:

  • 完美运行!
【解决方案2】:

我在为此目的创建MiniConsole 时遇到了这个问题。

我使用了你的技术

pro.EnableRaisingEvents = true;
pro.OutputDataReceived +=new DataReceivedEventHandler(OnDataReceived);
pro.ErrorDataReceived +=new DataReceivedEventHandler(OnDataReceived);

奇怪的是所有输出都来自 ErrorDataReceived 而不是 OutputDataReceived(使用有效命令)。

所以我认为你错过了:

pro.BeginErrorReadLine();

我也在主线程中启动进程(我没有任何工作线程),使用 python27。

这里是完整的开始:

        // executable: "c:\\python27\\python.exe", arguments: "myscript.py"
        ProcessStartInfo startInfo = new ProcessStartInfo(executable, arguments);
        startInfo.CreateNoWindow = true;
        startInfo.UseShellExecute = false;
        startInfo.RedirectStandardOutput = true;
        startInfo.RedirectStandardError = true;
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.WorkingDirectory = textBoxWorkingDirectory.Text;

        try
        {
            Process p = new Process();
            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();
        }

【讨论】:

    【解决方案3】:

    我记得不久前遇到过类似的问题,我想我在 .py 脚本中做了类似的事情,而不是使用 print 函数:

    sLog = 'Hello World!'
    subprocess.Popen( 'echo ' + sLog, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True )
    

    不确定我是否将shell 参数设置为TrueFalse。也不确定所有“std”参数。您可能想在那里进行一些实验。

    【讨论】:

      【解决方案4】:

      如果您从代码开始 Python 进程,那么 THIS 会让您的生活真正变得轻松,我认为这是最干净的方式。

      【讨论】:

        猜你喜欢
        • 2022-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多