c# - 如何从 C# 应用程序调用 (Iron)Python 代码?

标签 c# python ironpython

有没有一种方法可以使用我假设的 IronPython 从 C# 调用 Python 代码?如果是,怎么办?

最佳答案

这个过程很简单,尤其是在 C#/.NET 4 应用程序中,通过使用 dynamic 改进了对动态语言的支持。类型。但这最终取决于您打算如何在应用程序中使用 (Iron)Python 代码。你总是可以运行 ipy.exe作为一个单独的进程并传递你的源文件,以便它们可以被执行。但您可能希望在 C# 应用程序中托管它们。这给您留下了很多选择。

  1. 添加对 IronPython.dll 的引用和 Microsoft.Scripting.dll组件。您通常会在根 IronPython 安装目录中找到它们。

  2. 添加using IronPython.Hosting;到源代码的顶部并使用 Python.CreateEngine() 创建 IronPython 脚本引擎的实例.

  3. 这里有几个选项,但基本上您会创建一个 ScriptScopeScriptSource并将其存储为 dynamic多变的。这允许您执行它或从 C# 操作范围(如果您选择这样做)。

选项 1:

使用 CreateScope()创建一个空的 ScriptScope直接在 C# 代码中使用,但可在 Python 源代码中使用。您可以将这些视为解释器实例中的全局变量。

dynamic scope = engine.CreateScope();
scope.Add = new Func<int, int, int>((x, y) => x + y);
Console.WriteLine(scope.Add(2, 3)); // prints 5

选项 2:

使用 Execute()执行字符串中的任何 IronPython 代码。您可以在可以传入 ScriptScope 的地方使用重载存储或使用代码中定义的变量。

var theScript = @"def PrintMessage():
    print 'This is a message!'

PrintMessage()
";

// execute the script
engine.Execute(theScript);

// execute and store variables in scope
engine.Execute(@"print Add(2, 3)", scope);
// uses the `Add()` function as defined earlier in the scope

选项 3:

使用 ExecuteFile()执行 IronPython 源文件。您可以在可以传入 ScriptScope 的地方使用重载存储或使用代码中定义的变量。

// execute the script
engine.ExecuteFile(@"C:\path\to\script.py");

// execute and store variables in scope
engine.ExecuteFile(@"C:\path\to\script.py", scope);
// variables and functions defined in the scrip are added to the scope
scope.SomeFunction();

选项 4:

使用 GetBuiltinModule()ImportModule()扩展方法来创建一个范围,其中包含在所述模块中定义的变量。必须在搜索路径中设置以这种方式导入的模块。

dynamic builtin = engine.GetBuiltinModule();
// you can store variables if you want
dynamic list = builtin.list;
dynamic itertools = engine.ImportModule("itertools");
var numbers = new[] { 1, 1, 2, 3, 6, 2, 2 };
Console.WriteLine(builtin.str(list(itertools.chain(numbers, "foobar"))));
// prints `[1, 1, 2, 3, 6, 2, 2, 'f', 'o', 'o', 'b', 'a', 'r']`

// to add to the search paths
var searchPaths = engine.GetSearchPaths();
searchPaths.Add(@"C:\path\to\modules");
engine.SetSearchPaths(searchPaths);

// import the module
dynamic myModule = engine.ImportModule("mymodule");

您可以在 .NET 项目中做很多托管 Python 代码的工作。 C# 有助于弥合这种更容易处理的差距。结合此处提到的所有选项,您几乎可以做任何您想做的事情。当然,您可以使用 IronPython.Hosting 中的类做更多事情。命名空间,但这应该足以让您入门。

关于c# - 如何从 C# 应用程序调用 (Iron)Python 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7053172/

相关文章:

c# - ServiceBusConnection 异常 - 接收传输出现故障

python - 使用 Python(selenium)自动 9GAG 注释被删除?

Python 计算特定列的相同值

wpf - 数据绑定(bind) WPF + IRONPYTHON

c# - ListView 中的 WPF 按钮在 ViewModel 中看不到命令

C#:stacktrace 上的行号指向与 } 一致的行

python - 在python3中,如何测试工作空间根目录下的.py文件?

c# - 在 IronPython 中访问 C# 类成员

ironpython - 如何将 IronPython 作为脚本运行

c# - 如何对锁定语句进行单元测试?