是否可以将包含许多包的 Python 脚本嵌入到 C# 中?

Is it possible to embed Python script with many packages to C#?

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

有什么办法可以做到吗?

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 脚本与 .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 库不完全兼容。