python clr out_PythonNet:Python 与 .NET 公共语言运行库 (CLR)的几乎无缝集成

pythonnet - Python.NET

Python.NET is a package that gives Python programmers nearly seamless integration with the .NET Common Language Runtime (CLR) and provides a powerful application scripting tool for .NET developers. It allows Python code to interact with the CLR, and may also be used to embed Python into a .NET application.

Calling .NET code from Python

Python.NET allows CLR namespaces to be treated essentially as Python packages.

import clr

from System import String

from System.Collections import *

To load an assembly, use the AddReference function in the clr module:

import clr

clr.AddReference("System.Windows.Forms")

from System.Windows.Forms import Form

Embedding Python in .NET

All calls to python should be inside a using (Py.GIL()) {/* Your code here */} block.

Import python modules using dynamic mod = Py.Import("mod"), then you can call functions as normal, eg mod.func(args).

Use mod.func(args, Py.kw("keywordargname", keywordargvalue)) or mod.func(args, keywordargname: keywordargvalue) to apply keyword arguments.

All python objects should be declared as dynamic type.

Mathematical operations involving python and literal/managed types must have the python object first, eg. np.pi * 2 works, 2 * np.pi doesn't.

Example

static void Main(string[] args)

{

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 = np.cos(5) + sin(5);

Console.WriteLine(c);

dynamic a = np.array(new List { 1, 2, 3 });

Console.WriteLine(a.dtype);

dynamic b = np.array(new List { 6, 5, 4 }, dtype: np.int32);

Console.WriteLine(b.dtype);

Console.WriteLine(a * b);

Console.ReadKey();

}

}

Output:

1.0

-0.958924274663

-0.6752620892

float64

int32

[ 6. 10. 12.]

Resources

Information on installation, FAQ, troubleshooting, debugging, and projects using pythonnet can be found in the Wiki:

.NET Foundation

This project is supported by the .NET Foundation.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值