该过程非常简单,尤其是在C#/。NET
4应用程序中,该应用程序通过使用该
dynamic类型改进了对动态语言的支持。但这最终取决于您打算如何在应用程序中使用(Iron)Python代码。您始终可以
ipy.exe作为一个单独的进程运行,并传入您的源文件,以便可以执行它们。但是您可能想将它们
托管 在C#应用程序中。这给您留下了很多选择。
添加对
IronPython.dll
和Microsoft.scripting.dll
程序集的引用。通常,您都会在IronPython的根安装目录中找到它们。添加
using IronPython.Hosting;
到源代码的顶部,并使用来创建IronPython脚本引擎的实例Python.CreateEngine()
。您可以从此处获得几个选择,但是基本上您可以创建一个
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命名空间中的类进行更多操作,但这足以使您入门。



