简体   繁体   English

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

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

I need to embed some python scripts in C# application.我需要在 C# 应用程序中嵌入一些 python 脚本。 The problem is these scripts use many packages like numpy, openCV etc. I've read that Ironpython may handle such embedding but it's limited to pure Python code without any packages.问题是这些脚本使用了许多包,如 numpy、openCV 等。我读过 Ironpython 可以处理这种嵌入,但它仅限于纯 Python 代码,没有任何包。 It would be awesome to have such script as an object in C# app so I would call it every time I need without redundant input/output operations.在 C# 应用程序中拥有像 object 这样的脚本会很棒,所以我每次需要时都会调用它,而无需冗余输入/输出操作。 Time and performance are of the essence, beacause operations are performed on data captured from camera on Python script.时间和性能至关重要,因为操作是在 Python 脚本上对从摄像头捕获的数据执行的。

Is there any way to make it?有什么办法可以做到吗?

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();

        }
    }
}

If you need your python script to interact with .NET objects, you might take a look at the Python.NET package.如果您需要 python 脚本与 .NET 对象交互,您可以查看 Python.NET package。

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.
            }
        }
    }
}

You can pass named object to the Python engine with code like this:您可以使用如下代码将命名的 object 传递给 Python 引擎:

scope.Set("person", pyPerson);

you can find more examples, including examples how to access .NET objects here:您可以在此处找到更多示例,包括如何访问 .NET 对象的示例:

http://pythonnet.github.io/ http://pythonnet.github.io/

Using IronPython would be another possibility, but it supports Python 2.7 syntax and is not fully compatible with some Python libraries.使用 IronPython 是另一种可能性,但它支持 Python 2.7 语法,并且与某些 Python 库不完全兼容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM