[IronPython] How to call IronPython Interpreter with C# code?
Martin Maly
martmaly at exchange.microsoft.com
Thu Jul 21 22:50:12 CEST 2005
You can call IronPython through the IronPython.Hosting.PythonEngine
object.
Here's a trivial example:
using IronPython.Hosting;
class Program {
static void Main(string[] args) {
PythonEngine engine = new PythonEngine();
Console.WriteLine( engine.Evaluate("2 + 2") );
}
}
To get this to compile, add reference to IronPython.dll
The other interesting methods on PythonEngine are:
public void AddToPath(string dirName); ... adds path to
sys.path
public void Execute(string text);
public object Evaluate(string expr);
public void ExecuteFile(string fileName);
public int RunFileInNewModule(string fileName);
Here is another example, little more interesting, I think. The program
(running as Embed.exe) will
execute the Python statement, which in turn will load the Embed's type
information and modify the static field.
using System;
using IronPython.Hosting;
namespace Embed {
public class Program {
public static int Value = 0;
static void Main(string[] args) {
PythonEngine engine = new PythonEngine();
engine.Execute(
"import sys \n" +
"sys.LoadAssemblyByName(\"Embed\") \n"+
"import Embed \n" +
"Embed.Program.Value = 20 \n");
Console.WriteLine(Value);
}
}
}
And the last example that goes even further and uses SetVariable method:
using System;
using IronPython.Hosting;
using System.Windows.Forms;
namespace Embed {
public class Program {
static void Main(string[] args) {
PythonEngine engine = new PythonEngine();
Form form = new Form();
engine.SetVariable("form", form);
engine.Execute(
"import sys \n"
+
"sys.LoadAssemblyByName('System.Windows.Forms') \n"
+
"from System.Windows.Forms import Button \n"
+
"def on_exit(*args): \n"
+
" Application.Exit() \n"
+
"b = Button(Text='Exit') \n"
+
"b.Click += on_exit \n"
+
"form.Controls.Add(b) \n"
+
"form.Show()
\n");
Application.Run();
}
}
}
I hope this helps.
Martin
-----Original Message-----
From: users-ironpython.com-bounces at lists.ironpython.com
[mailto:users-ironpython.com-bounces at lists.ironpython.com] On Behalf Of
shhgs
Sent: Wednesday, July 20, 2005 4:18 PM
To: users-ironpython.com at lists.ironpython.com
Subject: [IronPython] How to call IronPython Interpreter with C# code?
Can somebody tell me how to call IronPython Interpreter with C# code, so
that I can embed Python into the .NET application.
Thank you!
More information about the Ironpython-users
mailing list