- Embedding Python Scripts in .NET Applications
- Identifying Source Code and Project
- Embedding the Script
- Conclusion
Embedding the Script
The next step is to actually embed the script. You start by using the scripting engine to set up a Python scripting engine instance. You can also set up any special paths your script will need before adding the script:
ScriptEngine pyEngine = Python.CreateEngine(); pyEngine.Runtime.IO.RedirectToConsole(); var paths = pyEngine.GetSearchPaths(); paths.Add(@"C:\Python27\Lib"); paths.Add(@"C:\Python27\Lib\site-packages"); pyEngine.SetSearchPaths(paths);
Line 2 tells the .NET framework that the Python Engine runtime will redirect its output to the console. However, this is not redirecting the new dialog for the tool we added to the application. (The code to do this appears below.)
But first, we need to add the actual script using a simple string variable. You have to change any quotes in your script to work within a double-quoted string.
An easy way to do this is simply replacing any double quotes in your script with single quotes. The syntax for embedding your script is as follows:
string thescript = @" (actual script text appears here) ";
You may have to play with the formatting a bit, but the indentation should be the same. After the script string resolves to a valid string, it is time to add in the redirect output code that displays the script's output to the new tool's dialog window:
Console.SetOut(TextWriter.Synchronized(new TextBoxWriter(statusText))); pyEngine.Execute(thescript); this.AllDone(FINISHED); } catch (Exception ex) { this.AllDone(ex.InnerException.StackTrace); } } public void AllDone(string message) { buttonStart.Enabled = true; this.statusLabel.Text = message; }
In the code above, we set up a new TextWriter that takes in a new type called TextBoxWriter, which allows us to write the script's output back to a text box. The code for the TextBoxWriter type is the following:
public 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; } } } }
The statusText property being passed into the TextBoxWriter type is our display text box that appears on the dialog displaying the output of the script. Every print statement in our Python script gets redirected to this text box.