是否可以在.NET应用程序中运行python?

问题描述:

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

In .NET application is possible save C# code in text file or database as string and run dynamically on the fly. This method is useful in many case such as business rule engine or user defined calculation engine and etc. Here is a nice example:

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,它利用编译器可以即时编译代码。

The class of primary importance here is the CSharpCodeProvider which utilises the compiler to compile code on the fly.

您知道Python是一种广泛使用的通用高级编程语言。它的设计理念强调代码的可读性,但是C#很难像python一样。因此,最好将python用于动态代码片段,而不是C#。

As you know Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, but C# is difficult that python. So it's better use python for dynamic code fragments instead C#.

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

How to execute python dynamically in C# application?

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
    }
}


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

IronPython is an implementation of the Python programming language in .NET (C#). After .NET version 4.0, IronPython's code can be embedded in .NET application with the help of the DLR (Dynamic Language Runtime).

嵌入日期的示例: http://www.codeproject .com / Articles / 602112 / Scripting-NET-Applications-with-IronPython

您还可以阅读用于动态语言运行时的MSDN 及其*以获取有关该主题的更多信息。

You can also read the MSDN For Dynamic Language Runtime and its Wikipedia to get additional info on the topic.

Google上也有很多教程在如何将IronPython嵌入.NET中

Google is also full of tutorials on "How to embed IronPython in .NET".

希望这会有所帮助!