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

 少年tyrty 发布于 2023-01-19 16:59

在.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() { { "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().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
    }
}

Paulo Bu.. 6

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

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

您还可以阅读MSDN For Dynamic Language Runtime及其Wikipedia以获取有关该主题的其他信息.

Google还提供了有关"如何在.NET中嵌入IronPython"的教程.

希望这可以帮助!

1 个回答
  • IronPython是.NET(C#)中Python编程语言的一种实现.在.NET 4.0之后,借助DLR(动态语言运行时),可以将IronPython的代码嵌入到.NET应用程序中.

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

    您还可以阅读MSDN For Dynamic Language Runtime及其Wikipedia以获取有关该主题的其他信息.

    Google还提供了有关"如何在.NET中嵌入IronPython"的教程.

    希望这可以帮助!

    2023-01-19 17:03 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有