views:

119

answers:

2

Hi,

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.

+1  A: 

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

djlawler
isn't my answer essentially the same as Tom E's? Is it because of the link, or is it because Tom's answer is better focused? Not complaining...just curious.
djlawler
Jeff Hardy
I expect that is it then :)I will file that away for future reference...
djlawler
+3  A: 

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());
Tom E
Hey,This is getting closer, I will try using it but with the dynamic keyword instead. I'll mark it as the answer if I can get it to work :-)
TimothyP
Looked into this some more, the problem here is that source.Execute(..) always returns null. The return type is dynamic, but the value is null. Runtime.UseFile(...) does return a value, I wonder why.
TimothyP