Running IronPython from C#

Download IronPython

public static void TestPython()
{
string code = @"100 * 2 + 4 / 3";

ScriptEngine engine = Python.CreateEngine();
ScriptSource source =
engine.CreateScriptSourceFromString(code, SourceCodeKind.Expression);

int res = source.Execute<int>();
Console.WriteLine(res);
}

public static void TestPython2()
{
ScriptEngine engine = Python.CreateEngine();
ScriptRuntime runtime = engine.Runtime;
ScriptScope scope = runtime.CreateScope();

string code = @"emp.Salary * 0.3";

ScriptSource source =
engine.CreateScriptSourceFromString(code, SourceCodeKind.Expression);

Employee emp = new Employee(1000,"Bernie",1000);

scope.SetVariable("emp", emp);

double res = (double)source.Execute(scope);

Console.WriteLine(res);
}

public static void TestPython3()
{
DataTable dt = new DataTable("test");
dt.Columns.Add("One", typeof(int));
dt.Columns.Add("Two", typeof(int));
dt.Columns.Add("Three", typeof(int));
for (int i = 0; i < 5; i++)
{
DataRow row = dt.NewRow();
row["One"] = 1 + 10 * i;
row["Two"] = 2 + 10 * i;
row["Three"] = 3 + 10 * i;
dt.Rows.Add(row);
}

ScriptEngine engine = Python.CreateEngine();
ScriptRuntime runtime = engine.Runtime;
ScriptScope scope = runtime.CreateScope();

string code = @"dt['One'] * 12";

ScriptSource source = engine.CreateScriptSourceFromString(code, SourceCodeKind.Expression);

scope.SetVariable("dt", dt.Rows[1]);

object res = source.Execute(scope);

Console.WriteLine(res);
}

Comments

Popular posts from this blog

Tibco Rendezvous (tibrv) C# .Net example

Parse XML to dynamic object in C#