Laxion
Laxion

Reputation: 39

IronPython | Redirect Output To Textbox

Ok so, let's say I am executing a script with IronPython in C#:

ScriptEngine engine = Python.CreateEngine();
string Script = textBox1.Text();
engine.Execute(Script);

Now let's say the script was:

print("Hello")

Output in VS Console: Hello What I am trying to achieve here is to redirect that output to a TextBox in C#. I have tried the following method which didn't work:

class TextBoxWriter : TextWriter
{
    private RichTextBox _textBox;

    public TextBoxWriter(RichTextBox textbox)
    {
        _textBox = textbox;
    }

    public override void Write(char value)
    {
        base.Write(value);
        _textBox.AppendText(value.ToString());
    }

    public override System.Text.Encoding Encoding
    {
        get { return System.Text.Encoding.UTF8; }
    }
}

Form1_Load:

engine.Runtime.IO.RedirectToConsole();
TextWriter _writer = TextWriter.Synchronized(new TextBoxWriter(textBox1));
Console.SetOut(_writer);

Upvotes: 1

Views: 717

Answers (1)

Frenchy
Frenchy

Reputation: 17037

I have just that in my code and its functional for me.

engine.Runtime.IO.RedirectToConsole();    
Console.SetOut(new TextBoxWriter(textBox1)); 

Upvotes: 1

Related Questions