10

I am just looking into using IronPython with C# and cannot seem to find any great documentation for what I need. Basically I am trying to call methods from a .py file into a C# program.

I have the following which opens the module:

var ipy = Python.CreateRuntime();
var test = ipy.UseFile("C:\\Users\\ktrg317\\Desktop\\Test.py");

But, I am unsure from here how to get access to the method inside there. The example I have seen uses the dynamic keyword, however, at work I am only on C# 3.0.

Thanks.

2 Answers 2

9

See embedding on the Voidspace site.

An example there, The IronPython Calculator and the Evaluator works over a simple python expression evaluator called from a C# program.

public string calculate(string input)
{
    try
    {
        ScriptSource source =
            engine.CreateScriptSourceFromString(input,
                SourceCodeKind.Expression);

        object result = source.Execute(scope);
        return result.ToString();
    }
    catch (Exception ex)
    {
        return "Error";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

7

You can try use the following code,

ScriptSource script;
script = eng.CreateScriptSourceFromFile(path);
CompiledCode code = script.Compile();
ScriptScope scope = engine.CreateScope();
code.Execute(scope);

It's from this article.

Or, if you prefer to invoke a method you can use something like this,

using (IronPython.Hosting.PythonEngine engine = new IronPython.Hosting.PythonEngine())
{
   engine.Execute(@"
   def foo(a, b):
   return a+b*2");

   // (1) Retrieve the function
   IronPython.Runtime.Calls.ICallable foo = (IronPython.Runtime.Calls.ICallable)engine.Evaluate("foo");

   // (2) Apply function
   object result = foo.Call(3, 25);
}

This example is from here.

Comments

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.