Stream Ironpython to my editor

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

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

We have our own editor (written in C #) that can load ironpython scripts and run it.

There are 2 problems that I need to solve.

  • If I have a print statement in ironpython script, how can I show it with my editor (how can I say that the python engine redirects the output to some handler in my C # code)

  • I plan to use unittest.py to run unittest. When I run the following runner = unittest.TextTestRunner () runner.run (Tests)

the output is redirected to standard output, but it needs to redirect it to the output window of the C # editor so that the user can see the results. This question may be related to 1

Any help is appreciated G

+4
source share
3 answers

You can provide a custom Stream or TextWriter that will be used for all output. You can provide them using one of the ScriptRuntime.IO.SetOutput overloads. Your Stream or TextWriter implementation should receive the strings and then output them to the editor window (possibly redirecting back to the user interface thread if you use a script for a second execution thread).

+6
source

Here is 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); 

To send a GUI to a user interface control, such as a text field, you need to create your own stream and implement it for the Write method, which will print to the text field.

+3
source

First you need to redirect the motor output to the console

 engine.Runtime.IO.RedirectToConsole(); 

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

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

And finally, you need to implement a 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; } } } } 

code>

Just really.

+2
source

All Articles