Hosting IronPython 2

The following C# code shows simple examples of using the IronPython 2 API to host IronPython in a .NET application. This code works with IronPython 2 beta 1.

using System; using IronPython.Hosting; using IronPython.Runtime; using Microsoft.Scripting; using Microsoft.Scripting.Hosting;

namespace EmbeddedCalculator {   public class Engine {       private ScriptEngine engine;

public Engine {           engine = PythonEngine.CurrentEngine; }

public string calculate(string input) {           try {               ScriptSource source = engine.CreateScriptSourceFromString(input, "py"); return source.Execute.ToString; }           catch {               return "Error"; }       }

} }

An alternative equivalent is: public class Engine {       private ScriptEngine engine; private ScriptScope scope;

public Engine {           engine = ScriptRuntime.Create.GetEngine("py"); scope = engine.CreateScope; }

public string calculate(string input) {           try {               ScriptSource source = engine.CreateScriptSourceFromString(input, SourceCodeKind.Expression); return source.Execute(scope).ToString; }           catch {               return "Error"; }       }

}

For returning a known type from Execute we could use int result = source.Execute (scope);.

Here's an example that sets some variables in the scope, executes some code, and then attempts to pull the variable 'x' back out of the scope: public class Engine {       private object button; private ScriptEngine engine; private ScriptScope scope;

public Engine {           engine = ScriptRuntime.Create.GetEngine("py"); scope = engine.CreateScope; }

public void set_button(object from_form) {           button = from_form; }

public string evaluate(string x, string code) {           scope.SetVariable("x", x); scope.SetVariable("button", button);

try {               ScriptSource source = engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements); source.Execute(scope); }           catch {               return "Error executing code"; }

if (!scope.VariableExists("x")) {               return "x was deleted"; }           string result = scope.GetVariable ("x").ToString; return result; }   }

Back to Contents.