我有以下代码(只是测试):
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));
}
但我想从字符串加载脚本。
答案 0 :(得分: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());
答案 1 :(得分:3)
这个例子可以在IronPython Cookbook帮助吗?它是关于如何从c#调用你的python类方法...但它包含一个从文件加载脚本的工作示例。该示例适用于IronPython 2.6(您必须小心哪个版本,因为他们已经更改了托管)。
http://www.ironpython.info/index.php/Using_Python_Classes_from_.NET/CSharp_IP_2.6