.NET/C#对Python的互操作 [英] .NET/C# Interop to Python

查看:48
本文介绍了.NET/C#对Python的互操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的后端是用.NET/C#编写的,我有一个要求,我需要执行从房屋.net端传递上下文的python脚本.它们在作为Windows服务运行的名为 hangfire 的后台任务引擎中排队.

My backend is written in .NET/C#, I have a requirement that I need to execute python scripts passing context from the .net side of the house. These are queued up in a background task engine called hangfire running as a windows service.

我做了一些挖掘,发现了 IronPython ,但是,在实现后,它无法支持许多pypi python软件包我需要在脚本中执行.

I did a little digging and found IronPython, however, after implementing it failed to support many of the pypi python packages that I need to execute inside my script.

其次,我查看了 Python.Net ,它是嵌入的嵌入式解释器或扩展CPython.CPython可以运行我需要的所有脚本/etc,但是,我发现始终打开/关闭python解释器会造成相当多的内存泄漏,并且那里始终也存在线程约束.有关某些详细信息,请参见文档.

Secondly, I looked at Python.Net which is a embedded interpreter that embeds or extends CPython. CPython can run all the scripts/etc that I needed, however, I found that opening/closing the python interpreter all the time can create quite a few memory leaks and there is always threading constraints there too. See docs for some of the details.

我想知道将这种互斥并嵌入python的方法是否是一个好主意.我想知道是否使用 celery 之类的东西使python成为自己的执行引擎,并使用类似的东西将两者之间的数据编组 protobufs 会是更好的解决方案?这增加了更多的复杂性,也给我的堆栈增加了一个任务引擎.

I'm wondering if this interopt and embedding python in .net is even a good idea. I'm wondering if making python its own execution engine using something like celery and marshalling data between the two using something like protobufs would be a better solution? This adds much more complexity and an additional task engine to my stack too.

我想知道是否还有其他人有任何想法/反馈/经验来尝试完成类似的任务?谢谢!

I was wondering if anyone else had any ideas/feedback/experiences trying to accomplishing something similar? Thanks!

推荐答案

我认为pythonnet是您最好的选择:

I would argue that pythonnet is your best option:

  1. 嵌入式Python解释器与Python子解释器不同.子解释器的使用要少得多,而CPython已嵌入主要应用程序中.此外,由于pythonnet会为您解决此问题,因此内存泄漏的可能性很小.
  2. 嵌入式解释器不必在两次调用之间关闭-实际上,这可能会非常昂贵,只要您的应用程序处于活动状态,您就可以使其保持持久状态.
  3. 如果使用(Py.GIL()){} 块将需要 GIL 的代码括在中,则可以避免
  4. 线程问题.
  5. 使用混合模式调试CPython/.NET代码的附加好处PTVS.
  1. Embedded Python interpreter is not the same as Python sub-interpreter. The sub-interpreter is used much less, while CPython has been embedded in major applications. Moreover memory leaks should be very unlikely due to pythonnet taking care of this for you.
  2. The embedded interpreter does not have to be shutdown between calls to it - in fact this can get very expensive, you can keep it persistent as long as your application is alive.
  3. Threading issues can be avoided if you enclose the code requiring the GIL with using (Py.GIL()) {} blocks.
  4. The added benefit of debugging CPython/.NET code in mixed-mode using PTVS.

这篇关于.NET/C#对Python的互操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆