IronPython - 在C#4.0应用程序中从字符串加载脚本

Tim*_*hyP 2 c# ironpython embedding

我有以下代码(只是一个测试):

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));
    }
Run Code Online (Sandbox Code Playgroud)

但我想从字符串加载脚本.

Tom*_*m E 7

您可以使用engine.CreateScriptSourceFromString从字符串而不是文件将脚本加载到作用域中.

     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());
Run Code Online (Sandbox Code Playgroud)