Further fun hosting IronPython
When I first got my Python host working, I could type expressions and they would run...but I couldn't see the output. I had to dig a little bit, but found that Python was sending its output to sys.stdout, which at startup is set to a PythonFile wrapping .NET's Console. To get what I wanted, I need to set sys.stdout to go back to my TextBox. To do this I added a couple of lines you've already seen. In the ConsolePane class, I wrote this:
TextBoxStream stream = new TextBoxStream(this.textBox);
this.processor = new PythonProcessor(stream);
and then in the PythonProcessor ctor, I set stdout:
sys.stdout = new PythonFile(outputStream, "w", false);
Then things worked nicely. Of course I had to write the TextBoxStream class. Fortunately, it only needed to write. Here's that code:
namespace AddInConsole
{
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
class TextBoxStream : Stream
{
private TextBox textBox = null;
public TextBoxStream(TextBox textBox)
{
this.textBox = textBox;
}
public override bool CanRead
{
get { return false; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return true; }
}
public override void Flush()
{
// Do nothing
}
public override long Length
{
get { return this.textBox.Text.Length; }
}
public override long Position
{
get
{
return this.textBox.CaretIndex;
}
set
{
throw new NotImplementedException("The method or operation is not implemented.");
}
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotImplementedException("Read not implemented");
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException("The method or operation is not implemented.");
}
public override void SetLength(long value)
{
throw new NotImplementedException("The method or operation is not implemented.");
}
public override void Write(byte[] buffer, int offset, int count)
{
// IronPython uses Encoding.ASCII to write to a stream...so we'll pull it back out
// the same way
byte[] convertBuffer = new byte[count];
Array.Copy(buffer, offset, convertBuffer, 0, count);
string output = Encoding.ASCII.GetString(convertBuffer);
this.textBox.AppendText(output);
}
}
}