[IronPython] How to call IronPython Interpreter with C# code?

Morgan Martinet ironpython at mmm-experts.com
Thu Jul 21 23:40:50 CEST 2005


Hi Martin,

Thanks for the examples!

> 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);
>         }
>     }
> }

Why don't you use the C# string notation that allows you to have multiple
lines of text (as in Python with the triple quote notation)?

         static void Main(string[] args) {
             PythonEngine engine = new PythonEngine();
             engine.Execute(@"
import sys
sys.LoadAssemblyByName('Embed')
import Embed
Embed.Program.Value = 20
");

 
> 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();
>         }
>     }
> }

Does it make any difference if you invoke Application.Run from the Python
script or from C#?

Thanks,

Morgan Martinet






More information about the Ironpython-users mailing list