Is it possible to run python in a .net application?

In a .net application, it is possible to save C # code in a text file or in a database as a string and execute dynamically on the fly. This method is useful in many cases, such as a business rule engine or a custom calculation engine, etc. here is a good 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));
    }
}

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

As you know, Python is a widely used high-level programming language. His design philosophy emphasizes code readability, but C # is more complicated than python. Therefore, it is better to use python for snippets of dynamic code instead of C #.

How to execute python dynamically in a 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
    }
}
+4
2

IronPython - Python .NET(#). .NET 4.0 IronPython .NET DLR (Dynamic Language Runtime).

, : http://www.codeproject.com/Articles/602112/Scripting-NET-Applications-with-IronPython.

MSDN Wikipedia, .

Google " IronPython .NET" .

, !

+4

IronPython - Python , .NET Framework. IronPython .NET Framework Python, .NET Python.

from http://ironpython.net/

. - Reflection Python (, CompileAssemblyFromSource), : http://social.msdn.microsoft.com/Forums/vstudio/en-US/9c72c404-eb6c-468b-bdbc-a6a91c55cdfe/c-ironpython-reflection?forum=csharpgeneral

0

Source: https://habr.com/ru/post/1530404/


All Articles