开发者

Streaming Ironpython output to my editor

We embed ironpython in our app sob that scripts can be executed in the context of our application.

I use Python.CreateEngine() and ScriptScope.Execute() to execute python scripts.

We have out own editor(written in C#) that can load ironpython scrip开发者_如何学Cts and run it.

There are 2 problems I need to solve.

  1. If I have a print statement in ironpython script, how can i show it my editor(how will I tell python engine to redirect output to some handler in my C# code)

  2. I plan to use unittest.py for running unittest. When I run the following runner = unittest.TextTestRunner() runner.run(testsuite)

the output is redirected to standard output but need a way for it to be redirected to my C# editor output window so that user can see the results. This question might be related to 1

Any help is appreciated G


You can provide a custom Stream or TextWriter which will be used for all output. You can provide those by using one of the ScriptRuntime.IO.SetOutput overloads. Your implementation of Stream or TextWriter should receive the strings and then output them to your editor window (potentially marshalling back onto the UI thread if you're running the script on a 2ndary execution thread).


Here's a snippet for sending output to a file.

       System.IO.FileStream fs = new System.IO.FileStream("c:\\temp\\ipy.log", System.IO.FileMode.Create);
       engine.Runtime.IO.SetOutput(fs, Encoding.ASCII);

For sending the GUI to a UI control, like a text box, you would need to create your own stream and have it implement a Write method that would print to the text box.


First you need to redirect the engine output to the console



    engine.Runtime.IO.RedirectToConsole();

Then you need to redirect the NET Console Out to a custom TextBox TextWriter. Here, your TextBox is txtBoxTarget



    // set application console output to the output text box
    Console.SetOut(TextWriter.Synchronized(new TextBoxWriter(txtBoxTarget)));

And finally you need to implement the custom TextBox TextWriter.

using System;
using System.IO;
using System.Windows.Forms;

namespace PythonScripting.TestApp
{
    class TextBoxWriter : TextWriter
    {
        private TextBox _textBox;

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


        public override void Write(char value)
        {
            base.Write(value);
            // When character data is written, append it to the text box.
            _textBox.AppendText(value.ToString()); 
        }

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

Simple, really.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜