2

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.

2 Answers 2

8

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());
Sign up to request clarification or add additional context in comments.

2 Comments

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 :-)
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.
3

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

2 Comments

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.
For me, sample code is preferable to a link, even if the code is copied & pasted. It's that little bit of extra effort that earns the vote.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.