pythonnet -Python.net
Python.net是一个包装,可为Python程序员与.NET通用语言运行时(CLR)几乎无缝集成,并为.NET开发人员提供功能强大的应用程序脚本工具。它允许Python代码与CLR交互,也可以将Python嵌入.NET应用程序中。
调用python的.NET代码
python.net允许将CLR名称空间从本质上处理为Python软件包。
import clr from System import String from System . Collections import *
要加载组件,请在clr模块中使用AddReference函数:
import clr clr . AddReference ( \"System.Windows.Forms\" ) from System . Windows . Forms import Form
默认情况下,单声道将用于Linux和MacOS,Windows上的.NET框架。有关加载不同运行时的详细信息,请参阅文档。
.NET核心
如果.NET CORE安装在默认位置或dotnet CLI工具在PATH上,则将其加载而不是默认(Mono/.Net Framework)运行时,只需要设置环境变量pythonnet _RUNTIME=coreclr还是调用pythonnet .load 。
pythonnet import load
load(\”coreclr\”)
import clr\”>
from pythonnet import load load ( \"coreclr\" ) import clr
将python嵌入.net中
- 您必须设置
Runtime.PythonDLL属性或pythonnet _PYDLL环境变量,从版本3.0开始,否则您将在调用Initialize时会收到BadPythonDllException(内部,源自MissingMethodException)。典型值是python38.dll(Windows),libpython3.8.dylib(Mac),libpython3.8.so(大多数其他类似Unix的操作系统)。 - 然后致电
PythonEngine.Initialize()。如果您打算使用多个线程中的Python对象,请致电PythonEngine.BeginAllowThreads()。 - 对Python的所有调用都应在
using (Py.GIL()) {/* Your code here */}块中。 - 使用
dynamic mod = Py.Import(\"mod\")导入python模块,然后您可以按正常方式调用函数,例如mod.func(args)。 - 使用
mod.func(args, Py.kw(\"keywordargname\", keywordargvalue))或mod.func(args, keywordargname: keywordargvalue)应用关键字参数。 - 所有python对象应声明为
dynamic类型。 - 涉及Python和文字/托管类型的数学操作必须首先具有Python对象。
np.pi * 2作品,2 * np.pi没有。
例子
static void Main ( string [ ] args ) { PythonEngine . Initialize ( ) ; using ( Py . GIL ( ) ) { dynamic np = Py . Import ( \"numpy\" ) ; Console . WriteLine ( np . cos ( np . pi * 2 ) ) ; dynamic sin = np . sin ; Console . WriteLine ( sin ( 5 ) ) ; double c = ( double ) ( np . cos ( 5 ) + sin ( 5 ) ) ; Console . WriteLine ( c ) ; dynamic a = np . array ( new List < float > { 1 , 2 , 3 } ) ; Console . WriteLine ( a . dtype ) ; dynamic b = np . array ( new List < float > { 6 , 5 , 4 } , dtype : np . int32 ) ; Console . WriteLine ( b . dtype ) ; Console . WriteLine ( a * b ) ; Console . ReadKey ( ) ; } }
输出:
1.0 - 0.958924274663 - 0.6752620892 float64 int32 [ 6 . 10 . 12 . ]
资源
可以在Wiki中找到有关使用pythonnet的安装,常见问题,故障排除,调试和项目的信息:
https://gi*t*hu*b.com/pythonnet/ pythonnet /wiki
- 邮件列表
- https://mail.py*t*h*on.org/mailman/listinfo/pythondotnet
- 聊天
- https://git**ter.i*m/pythonnet/ pythonnet
.NET基金会
该项目得到了.NET基金会的支持。
