IronPython vs. Python .NET
我想从Python代码访问一些用C#编写的.NET程序集。
一项小小的研究表明,我有两种选择:
- 内置.NET接口功能/支持的IronPython
- 带有Python .NET包的Python
两种解决方案之间的权衡是什么?
如果您想主要基于.NET框架编写代码,则强烈建议IronPython与Python.NET。 IronPython几乎是.NET的本机-因此,与其他.NET语言集成时,它的工作非常出色。
如果您只想将.NET中的一个或两个组件集成到标准python应用程序中,则Python.NET很好。
使用IronPython时,有明显的不同-但大多数都相当细微。 Python.NET使用标准的CPython运行时,因此,此Wiki页面是有关两种实现之间差异的相关讨论。最大的差异发生在异常的代价上-因此,由于其实现,某些标准的python库在IronPython中的性能不佳。
在同意里德·科普西(Reed Copsey)和亚历克斯·马特利(Alex Martelli)给出的答案的同时,我想指出另外一个区别-全球口译员锁定(GIL)。尽管IronPython不受GIL的限制,但CPython却具有-因此,对于那些GIL成为瓶颈的应用程序,例如在某些多核方案中,IronPython比Python.NET更具优势。
从Python.NET文档中:
Important Note for embedders: Python
is not free-threaded and uses a global
interpreter lock to allow
multi-threaded applications to
interact safely with the Python
interpreter. Much more information
about this is available in the Python
C API documentation on the
www.python.org Website.When embedding Python in a managed
application, you have to manage the
GIL in just the same way you would
when embedding Python in a C or C++
application.Before interacting with any of the
objects or APIs provided by the
Python.Runtime namespace, calling code
must have acquired the Python global
interpreter lock by calling the
PythonEngine.AcquireLock method. The
only exception to this rule is the
PythonEngine.Initialize method, which
may be called at startup without
having acquired the GIL.When finished using Python APIs,
managed code must call a corresponding
PythonEngine.ReleaseLock to release
the GIL and allow other threads to use
Python.The
AcquireLock andReleaseLock
methods are thin wrappers over the
unmanagedPyGILState_Ensure and
PyGILState_Release functions from the
Python API, and the documentation for
those APIs applies to the managed
versions.
另一个问题是IDE支持。 CPython当前可能比IronPython具有更好的IDE支持-因此这可能是一个选择另一个的因素。
大多数依赖CPython C-API的科学和数字Python库(numpy,scipy,matplotlib,pandas,cython等)大多在CPython下工作,因此在这种情况下,最好的选择是pythonnet(其他名称-Python.NET和适用于.NET的Python)。
对于CPython GUI绑定,例如WxWidgets,PyQt / PySide,GTK,Kivy等,也是如此,尽管pythonnet和IronPython都可以使用WPF和WinForms。
最后,IronPython还不完全支持Python 3。
IronPython是" .NET原生"的-因此,如果您想将Python代码与.NET完全集成在一起,那将是更好的选择。 Python.NET与经典Python一起使用,因此它使您可以远离.NET适当地保持Python代码的"正常长度"。 (请注意,通过此代码,您实际上可以使用IronPython代码中为CPython编写的扩展,因此不再是区分条件。)
IronPython来自Microsoft,因此我会坚持不懈地使用它,因为您必须假定它可以与其他MSFT技术更好地结合使用。
至于2016年
在我的公司中,我们使用IronPython,但对性能不满意(大多数情况下使用内存-垃圾收集器太慢),因此我们决定切换到标准Python,并使用Zeroce-s ICE将其与.Net集成。
IronPython当前不支持Python 3.6(仅2.7)
IronPython 3中的"尚未提供IronPython 3的构建。"
Ironpython就像C#一样,它依赖于静态的预构建库,而C#是一种动态语言。
Cpython就像C ++一样,就像Ironpython是一种动态语言,并且可以访问动态库,而动态库又转化为被迫编写所有内容。
Ironpython在某些方面比C#快,但不比Cpython快,但是您可以将Ironpython链接到任何语言,从而解决出现的问题,但是再次可以对Cpython执行相同的操作。
无论选择什么,都是一种有趣,简单而强大的语言!
Iron Python基本上是集成了.net支持的Python 2.7,它可能永远不会支持Python3。它在C和Python库中失传了,但是在另一方面,它可以访问.net并可以使用C#进行扩展。因此,如果您已经使用C#,那么Iron Python是一个加分项。
我主要喜欢.NET的Python,因为IronPython被编译为托管代码,可以很容易地反编译(我最讨厌的),但是使用py2exe或pyinstaller,您可以将带有NET模块的Python编译为非托管应用程序。