我已经在这个问题上工作了一段时间显示它。我可以捕获控制台窗口的输出(live),但我无法捕获实时中的python控制台应用程序的输出。我可以在运行完成后捕获python程序的输出,但我不想那样。 我使用从system.diagonistics过程。与一名背景工作者。 我只是想捕捉的python26输出到一个文本框。我已经用其他自定义应用程序测试过我的程序,并且它显示输出(实时)。C#捕获python.exe输出,并在文本框
请帮助
感谢
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 \ n – rerun 2011-05-11 16:59:43
Ironpython文本框可能是您的目的的有用工具http://www.codeproject.com/KB/ miscctrl/irontextbox.aspx – lucemia 2011-05-11 17:13:53
你有没有想出解决办法? – Sugitime 2013-10-31 03:12:34