能否在.NET应用程序中运行Python?

9

在.NET应用程序中,可以将C#代码保存为文本文件或数据库中的字符串,并在运行时动态地执行。这种方法在许多情况下都非常有用,例如业务规则引擎或用户定义的计算引擎等。以下是一个很好的例子:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

class Program
{
    static void Main(string[] args)
    {
        var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
        var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
        parameters.GenerateExecutable = true;
        CompilerResults results = csc.CompileAssemblyFromSource(parameters,
        @"using System.Linq;
            class Program {
              public static void Main(string[] args) {
                var q = from i in Enumerable.Range(1,100)
                          where i % 2 == 0
                          select i;
              }
            }");
        results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
    }
}

在这里最重要的类是CSharpCodeProvider,它利用编译器来实时编译代码。

正如您所知道的,Python是一种广泛使用的通用高级编程语言。它的设计理念强调代码可读性,但与Python相比,C#更加困难。因此,在动态代码片段方面最好使用Python而不是C#。

如何在C#应用程序中动态执行Python?

class Program
{
    static void Main(string[] args)
    {
        var pythonCode = @"
                a=1
                b=2
                c=a+b
                return c";
        //how to execute python code in c# .net
    }
}

1
你听说过IronPython吗? - Paulo Bu
请问您能否分享更多细节,我只在NuGet上看到了这个。 - Hadi Sharifi
我也在编辑问题,将IronPython作为标签包含进去,因为这可能会带来更有用的答案 :) - Paulo Bu
1
PythonNet也是一个选择。我相信它与其他Python模块的兼容性更好。 - M4rtini
@M4rtini,能否提供一个简单的示例? - Hadi Sharifi
Python for .NET是另一种方式——允许您从Python中调用C#代码。如果您想本地从C#调用Python,则只有IronPython可以做到这一点。 - Corley Brigman
2个回答

8

IronPython是Python编程语言在.NET(C#)中的一种实现。在.NET 4.0版本之后,可以通过DLR(动态语言运行时)将IronPython的代码嵌入到.NET应用程序中。

以下是一个非常合理的最新示例,展示如何嵌入它:http://www.codeproject.com/Articles/602112/Scripting-NET-Applications-with-IronPython

您还可以阅读MSDN For Dynamic Language RuntimeWikipedia以获取有关此主题的其他信息。

Google也充满了有关"如何在.NET中嵌入IronPython"的教程。

希望这能帮到您!


0
IronPython是Python编程语言的开源实现,与.NET Framework紧密集成。 IronPython可以使用.NET Framework和Python库,其他.NET语言也可以像使用Python代码一样轻松地使用它们。
他们的网站上有与Visual Studio集成的工具。如果您的目标是在运行时使用反射和编译Python代码(例如使用CompileAssemblyFromSource方法),则可以查看此链接: http://social.msdn.microsoft.com/Forums/vstudio/en-US/9c72c404-eb6c-468b-bdbc-a6a91c55cdfe/c-ironpython-reflection?forum=csharpgeneral

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接