Search code examples
pythonc#embedclrironpython

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


I need to embed some python scripts in C# application. 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. 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. Time and performance are of the essence, beacause operations are performed on data captured from camera on Python script.

Is there any way to make it?


Solution

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