代码之家  ›  专栏  ›  技术社区  ›  TimothyP

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

  •  2
  • TimothyP  · 技术社区  · 15 年前

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

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

    但是我想从字符串加载脚本。

    2 回复  |  直到 10 年前
        1
  •  7
  •   Tom E    15 年前

    你可以用 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());
    
        2
  •  3
  •   djlawler    15 年前

    IronPython食谱中的这个例子是否有帮助?它是关于如何从c#调用python类方法的,但它也包含了一个从文件加载脚本的工作示例。该示例适用于IronPython2.6(您必须小心哪个版本,因为他们已经对宿主进行了相当多的更改)。

    http://www.ironpython.info/index.php/Using_Python_Classes_from_.NET/CSharp_IP_2.6