繁体   English   中英

python 在 C# 应用程序中的集成

[英]Integration of python in C# Application

我有以下问题:我有一个用 python 编写的旧应用程序。 此应用程序允许用户指定将执行的小 python 步骤,python 步骤基本上是小 python 脚本,我称它们为步骤是因为此应用程序的执行涉及其他步骤,例如从命令行执行某些操作。 这些 python 步骤作为 python 代码存储在 xml 文件中。

现在我想使用 C# .NET 重写应用程序。 是否有最佳实践解决方案来做这样的事情?

I don't want to call python as external programm and pass the actual python step(script) to the python interpreter - I want something built in. I just came across IronPython and .NET python but I am not quite sure which one to use. 我想为小脚本实现某种调试,这就是为什么调用解释器解决方案是不可接受的。

更重要的是,很多这些脚本已经存在。 因此,我必须使用 python 的 C# 实现,它具有与 python 相同的语法以及相同的内置库 Z23EEEB4347BDD25DZDB63B。 这甚至可能吗?

感谢和问候 Xeun

IronPython就是你想要的。 它编译为.NET字节码。 您可以合理地轻松地从另一种.NET语言调用python代码(反之亦然)。 我认为,Visual Studio也支持IronPython。

可以使用IronPython从C#执行Python脚本。

    var ipy = Python.CreateRuntime();
    dynamic test = ipy.UseFile("Test.py");
    test.Simple();

也可以看看:

http://putridparrot.com/blog/hosting-ironpython-in-ac-application/

https://blogs.msdn.microsoft.com/charlie/2009/10/25/running-ironpython-scripts-from-ac-4-0-program/

您可以使用IronPython的ScriptScope.GetVariable来获取实际函数,然后您可以像C#函数一样调用它。 像这样使用它:

C#代码:

var var1, var2 = ...
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
engine.ExecuteFile(@"C:\test.py", scope);
dynamic testFunction = scope.GetVariable("test_func");
var result = testFunction(var1,var2);

Python代码:

def test_func(var1,var2):
    ...do something...

花了一些时间才弄明白,这很简单..而且IronPython是免费且易于使用的。 希望这可以帮助 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM