【问题标题】:IronPython - Load script from string in C# 4.0 applicationIronPython - 从 C# 4.0 应用程序中的字符串加载脚本
【发布时间】:2010-01-28 12:07:18
【问题描述】:

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

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

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

【问题讨论】:

    标签: c# ironpython embedding


    【解决方案1】:

    您可以使用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());
    

    【讨论】:

    • 嘿,这越来越近了,我会尝试使用它,但用动态关键字代替。如果我能让它工作,我会把它标记为答案:-)
    • 再看一遍,这里的问题是 source.Execute(..) 总是返回 null。返回类型是动态的,但值为 null。 Runtime.UseFile(...) 确实返回一个值,我想知道为什么。
    【解决方案2】:

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

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

    【讨论】:

    • 我的回答和 Tom E 的回答不一样吗?是因为链接,还是因为汤姆的回答更专注?不抱怨……只是好奇。
    • 对我来说,示例代码比链接更可取,即使代码是复制和粘贴的。正是这一点额外的努力才能赢得选票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多