可以在.NET应用程序中运行Python吗?

9 投票
2 回答
9691 浏览
提问于 2025-04-17 21:06

在.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是一种广泛使用的通用高级编程语言。它的设计理念强调代码的可读性,而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
    }
}

2 个回答

0

IronPython 是一个开源的 Python 编程语言实现,它和 .NET 框架紧密结合在一起。IronPython 可以使用 .NET 框架和 Python 库,其他 .NET 语言也可以很方便地使用 Python 代码。

来自 http://ironpython.net/

他们的网站上还有一些工具可以和 Visual Studio 集成。如果你想在运行时使用反射功能并编译 Python 代码(就像使用 CompileAssemblyFromSource 方法那样),你可以查看这个链接:http://social.msdn.microsoft.com/Forums/vstudio/en-US/9c72c404-eb6c-468b-bdbc-a6a91c55cdfe/c-ironpython-reflection?forum=csharpgeneral

8

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

这里有一个看起来很合理的最新示例,教你如何嵌入 IronPython:http://www.codeproject.com/Articles/602112/Scripting-NET-Applications-with-IronPython

你还可以阅读 MSDN 关于动态语言运行时 和它的 维基百科 页面,以获取更多相关信息。

在谷歌上也有很多关于 “如何在 .NET 中嵌入 IronPython” 的教程。

希望这些信息对你有帮助!

撰写回答