在C#中嵌入IronPython

Dar*_*ung 9 c# ironpython

我只是在研究使用IronPython和C#,似乎无法找到任何我需要的文档.基本上我试图将.py文件中的方法调用到C#程序中.

我有以下打开模块:

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

但是,我不确定如何访问其中的方法.我见过的例子使用了dynamic关键字,但是,在工作中我只使用C#3.0.

谢谢.

gim*_*mel 9

请参阅Voidspace网站上的嵌入.

在那里的一个例子,IronPython计算器和Evaluator 工作在一个从C#程序调用的简单python表达式求值程序.

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";
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

您可以尝试使用以下代码,

ScriptSource script;
script = eng.CreateScriptSourceFromFile(path);
CompiledCode code = script.Compile();
ScriptScope scope = engine.CreateScope();
code.Execute(scope);
Run Code Online (Sandbox Code Playgroud)

它来自这篇文章.

或者,如果你想调用一个方法,你可以使用这样的东西,

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);
}
Run Code Online (Sandbox Code Playgroud)

这个例子来自这里.