开发者

IronPython - Load script from string in C# 4.0 application

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.


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


Might this example at the IronPython Cookbook help? It is on how to call your python class methods from c#...but it contains a working example of loading a script from a file as well. The example works on IronPython 2.6 (you have to be careful which version as they have been changing the Hosting around quite a bit).

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜