我正在运行一个带有后台工作程序的Windows窗体,以根据python脚本的输出更新文本框。除了重定向的输出不是实时的,它一切都很好用;它的推迟非常显着。
任何想法如何增加重定向输出响应时间?
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 JiraHeartBeat
{
public partial class Form1 : Form
{
delegate void AppendTextDelegate(string text);
BackgroundWorker Worker = new BackgroundWorker();
public Form1()
{
InitializeComponent();
Worker.DoWork += new DoWorkEventHandler(Worker_DoWork);
Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Worker_RunWorkerCompleted);
}
void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
StartButton.PerformClick();
}
private void StartButton_Click(object sender, EventArgs e)
{
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);
pro.StartInfo.FileName = "C:\\Python27\\python.exe";
pro.StartInfo.Arguments = "\"C:\\Python27\\myscript.py\"";
try
{
pro.Start();
pro.BeginOutputReadLine();
pro.BeginErrorReadLine();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Thread.Sleep(5000 * 60);
}
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);
}
}
}
}
答案 0 :(得分:1)
实际上,问题是Python在脚本完成之前不会重定向输出。我相信IronPython会在脚本运行时重定向(虽然没有测试过)但不幸的是,常规Python必须等待脚本在重定向输出之前结束。
答案 1 :(得分:0)
尝试从Worker_DoWork
删除以下行,我怀疑它会延迟执行RunWorkerCompleted
事件。
Thread.Sleep(5000 * 60);
修改强>
由于尝试了上述方法并且没有完全解决问题,我进一步调查并确认当从python脚本捕获输出时响应被延迟。但是,通过添加对sys.stdout.flush()
的调用,我能够获得所需的行为。这是我使用的python脚本,它在我的测试中成功运行。
import time
import sys
for x in xrange(0,11):
print x
time.sleep(1)
sys.stdout.flush()