2

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

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

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

4

2 回答 2

8

您可以使用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());
于 2010-01-28T16:15:51.357 回答
3

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

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

于 2010-01-28T16:15:04.667 回答