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

标签 c# python .net dynamic ironpython

在 .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。所以动态代码片段最好使用 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
    }
}

最佳答案

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

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

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

Google 也充满了关于 "How to embed IronPython in .NET" 的教程。 .

希望这对您有所帮助!

关于c# - 是否可以在 .NET 应用程序中运行 python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22222459/

相关文章:

C# PCAP.NET 如何发送有效的 TCP 请求?

c# - 字典的 JSON 序列化为名称 :value instead of {name:name, 值:值}

python - 为什么通过从另一个模块调用函数来显示来自不同模块中不同 GUI 的图像时会出现问题?

python - copytree(),参数 symlink 和ignore 的作用是什么?

python - Python 中的照应列表理解

.net - ASP.Net Webforms 和 ASP.Net MVC 是基于组件还是基于 Action ?

c# - 使用进度从 FTP 下载文件 - TotalBytesToReceive 始终为 -1?

c# - 动态创建的 PDF 不在 64 位 IE9 窗口中嵌入/呈现内联

c# - 从 C# 调用默认浏览器?

原始内存流上的 C# 数学性能