我试图使用标准的输入和输出从C#控制python会话。在
启动Python进程后,我希望继续向它发送命令,并将输出接收到WinForms文本框。在
在尝试了许多SO答案和MSDN之后,对于为什么没有调用DataReceivedEvent
处理程序有什么建议吗?完整代码如下:
注意,要从Python生成换行符,我在命令文本import os;print os.linesep
中输入以下内容
using System;
using System.Diagnostics;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private static Process InterProc;
public Form1()
{
InitializeComponent();
InterProc = new Process();
InitializeInterpreter();
}
private void InitializeInterpreter()
{
InterProc.StartInfo.UseShellExecute = false;
InterProc.StartInfo.FileName = @"C:\Python27\python.exe";
InterProc.StartInfo.RedirectStandardInput = true;
InterProc.StartInfo.RedirectStandardOutput = true;
InterProc.StartInfo.RedirectStandardError = true;
InterProc.StartInfo.CreateNoWindow = true;
InterProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
InterProc.OutputDataReceived += new DataReceivedEventHandler(InterProcOutputHandler);
bool started = InterProc.Start();
InterProc.BeginOutputReadLine();
}
private void AppendTextInBox(TextBox box, string text)
{
if (this.InvokeRequired)
{
this.Invoke((Action<TextBox, string>)AppendTextInBox, OutputTextBox, text);
}
else
{
box.Text += text;
}
}
private void InterProcOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
AppendTextInBox(OutputTextBox, outLine.Data + Environment.NewLine);
}
private void Enterbutton_Click(object sender, EventArgs e)
{
InterProc.StandardInput.WriteLine(CommandTextBox.Text);
}
}
}
这个答案是为那些在这里着陆的人准备的,他们希望在众多的答案中找到另一个答案。
最终与python会话交互的代码如下:
注1:使用'-i'参数调用Python。(请参阅下面的流程参数
-i
)注意2:尝试同步读取std error freezed(
Process.StandardError.ReadToEnd()
)。因此std输出和错误流都需要提供处理程序回调(请参阅下面的InterProcOutputHandler
)相关问题 更多 >
编程相关推荐