栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

该过程非常简单,尤其是在C#/。NET
4应用程序中,该应用程序通过使用该

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

  1. 添加对

    IronPython.dll
    Microsoft.scripting.dll
    程序集的引用。通常,您都会在IronPython的根安装目录中找到它们。

  2. 添加

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

  3. 您可以从此处获得几个选择,但是基本上您可以创建一个

    scriptScope
    scriptSource
    将其存储为
    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。您可以在可以传递a的地方使用重载
scriptScope
来存储或使用代码中定义的变量。

var thescript = @"def PrintMessage():    print 'This is a message!'PrintMessage()";// execute the scriptengine.Execute(thescript);// execute and store variables in scopeengine.Execute(@"print Add(2, 3)", scope);// uses the `Add()` function as defined earlier in the scope

选项3:

使用

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

// execute the scriptengine.ExecuteFile(@"C:pathtoscript.py");// execute and store variables in scopeengine.ExecuteFile(@"C:pathtoscript.py", scope);// variables and functions defined in the scrip are added to the scopescope.SomeFunction();

选项4:

使用

GetBuiltinModule()
importModule()
扩展方法来创建包含在所述模块中定义的变量的范围。必须在搜索路径中设置以此方式导入的模块。

dynamic builtin = engine.GetBuiltinModule();// you can store variables if you wantdynamic 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 pathsvar searchPaths = engine.GetSearchPaths();searchPaths.Add(@"C:pathtomodules");engine.SetSearchPaths(searchPaths);// import the moduledynamic myModule = engine.importModule("mymodule");

您可以在.NET项目中做很多托管Python代码的工作。C#帮助弥合这一差距更容易解决。结合这里提到的所有选项,您几乎可以做任何事情。当然,您可以对

IronPython.Hosting
命名空间中的类进行更多操作,但这足以使您入门。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/617465.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号