IronPython的 - 从字符串在C#4.0的应用程序加载脚本 [英] IronPython - Load script from string in C# 4.0 application
本文介绍了IronPython的 - 从字符串在C#4.0的应用程序加载脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码(只是一个测试):
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.
推荐答案
您可以使用 engine.CreateScriptSourceFromString
将脚本加载到从范围。字符串,而不是一个文件
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());
这篇关于IronPython的 - 从字符串在C#4.0的应用程序加载脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文