Search code examples
c#ironpythonembedding

IronPython - Load script from string in C# 4.0 application


I have the following code (just a test):

var engine = Python.CreateEngine();
var runtime = engine.Runtime;

    try
    {                
        dynamic test = runtime.UseFile(@"d:\test.py");

        test.SetVariable("y", 4);
        test.SetVariable("client", UISession.ControllerClient);
        test.Simple();
    }
    catch (Exception ex)
    {
        var eo = engine.GetService<ExceptionOperations>();
        Console.WriteLine(eo.FormatException(ex));
    }

But I would like to load the script from a string instead.


Solution

  • You can use engine.CreateScriptSourceFromString to load the script into the scope from a string, rather than a file.

         StringBuilder sb = new StringBuilder();
         sb.Append("def helloworld():\r\n");
         sb.Append("    print \"hello world\"\r\n");
         string code = sb.ToString();
         ScriptEngine engine = Python.CreateEngine();         
         ScriptSource source = engine.CreateScriptSourceFromString(code, SourceCodeKind.File);
         ScriptScope scope = engine.CreateScope();
         source.Execute(scope);
         Func<object> func = scope.GetVariable<Func<object>>("helloworld");
         Console.WriteLine(func());