【问题标题】:Is it possible to embed Python script with many packages to C#?是否可以将带有许多包的 Python 脚本嵌入到 C# 中?
【发布时间】:2021-07-29 20:17:19
【问题描述】:

我需要在 C# 应用程序中嵌入一些 python 脚本。问题是这些脚本使用了许多包,如 numpy、openCV 等。我读过 Ironpython 可以处理这种嵌入,但它仅限于没有任何包的纯 Python 代码。将这样的脚本作为 C# 应用程序中的对象会很棒,所以我每次需要时都会调用它,而无需冗余输入/输出操作。时间和性能至关重要,因为操作是在 Python 脚本上对从摄像头捕获的数据执行的。

有什么办法吗?

【问题讨论】:

    标签: python c# embed clr ironpython


    【解决方案1】:
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Threading.Tasks;
    
    namespace App
    {
        public  class Test
        {
            
    
            private void runScript(object sender, EventArgs e)
            {
                run_cmd();
            }
    
            private void run_cmd()
            {
    
                string fileName = @"C:\app.py";
    
                Process p = new Process();
                p.StartInfo = new ProcessStartInfo(@"C:\path\python.exe", fileName)
                {
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                };
                p.Start();
    
                string output = p.StandardOutput.ReadToEnd();
                p.WaitForExit();
    
                Console.WriteLine(output);
    
                Console.ReadLine();
    
            }
        }
    }
    

    【讨论】:

    • 好的,但是打开的时间很长。你现在能告诉我现在是否可以从那个 python 脚本中获取一些数据吗?我需要做什么?
    • 我不确定,但是你为什么不把你的模型变成一个 Api 然后托管它并通过 C# 向模型端点发送请求,这比做所有这些要容易得多。跨度>
    • 我并不精通 C#。我有一个任务来包装我的脚本,以便其他人可以在 WPF 中加载它。我还有一个问题。有没有办法加载一次python(因为加载时间来查看脚本结果非常大)然后更快地运行特定的脚本?
    • 是的,只需将调用可执行文件的代码放在一个固定块中,而不是每次调用每个脚本时。
    【解决方案2】:

    如果您需要 Python 脚本与 .NET 对象交互,您可以查看 Python.NET 包。

    using Python.Runtime;
    
    class Test
    {
    
        void RunPython()
        {
            using (Py.GIL())
            {
                using (var scope = Py.CreateScope())
                {
                    var scriptFileName = "myscript.py";
                    var compiledFile = PythonEngine.Compile(File.ReadAllText(scriptFileName), scriptFileName);
    
                    scope.Execute(compiledFile); // can be compiled once, executed  multiple times.
                }
            }
        }
    }
    

    您可以使用如下代码将命名对象传递给 Python 引擎:

    scope.Set("person", pyPerson);
    

    您可以在此处找到更多示例,包括如何访问 .NET 对象的示例:

    http://pythonnet.github.io/

    使用 IronPython 是另一种可能性,但它支持 Python 2.7 语法并且与某些 Python 库不完全兼容。

    【讨论】:

      猜你喜欢
      • 2013-07-06
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 2010-12-26
      • 1970-01-01
      相关资源
      最近更新 更多