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

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

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(); Console.WriteLine(eo.FormatException(ex)); } 

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

您可以使用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 func = scope.GetVariable>("helloworld"); Console.WriteLine(func()); 

这个例子可以在IronPython Cookbook帮助吗? 它是关于如何从c#调用你的python类方法…但它包含一个从文件加载脚本的工作示例。 该示例适用于IronPython 2.6(您必须小心哪个版本,因为他们已经相当多地更改了托管)。

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