none
Calling Python script from Winform C# Application RRS feed

  • Question

  • I want to call a Python script from my winform C# application. I checked for some solutions and followed following approaches. One using Inter-Process communication and one using IronPython

    Approach 1 : Using Inter-Process Communication

    private void BtnSumPy_Click(object sender, EventArgs e)
        {
            string python = @"C:\Programs\Python\Python37-32\python.exe";
    
            // python app to call 
            string myPythonApp = @"C:\mypath\\SamplePy\SamplePy2\SamplePy2.py";
    
            // dummy parameters to send Python script 
            int x = 3;
            int y = 4;
    
            // Create new process start info 
            ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python);
    
            // make sure we can read the output from stdout 
            myProcessStartInfo.UseShellExecute = false;
            myProcessStartInfo.RedirectStandardOutput = true;
    
            // start python app with 3 arguments  
            // 1st arguments is pointer to itself,  
            // 2nd and 3rd are actual arguments we want to send 
            myProcessStartInfo.Arguments = myPythonApp + " " + x + " " + y;
    
            Process myProcess = new Process();
            // assign start information to the process 
            myProcess.StartInfo = myProcessStartInfo;
    
            // start the process 
            myProcess.Start();
    
            // Read the standard output of the app we called.  
            // in order to avoid deadlock we will read output first 
            // and then wait for process terminate: 
            StreamReader myStreamReader = myProcess.StandardOutput;
            string myString = myStreamReader.ReadLine();
    
            /*if you need to read multiple lines, you might use: 
                string myString = myStreamReader.ReadToEnd() */
    
            // wait exit signal from the app we called and then close it. 
            myProcess.WaitForExit();
            myProcess.Close();           
    
            lblAns.Text = myString;
        }

    The issue with above approach is that Python.exe will have to installed on the local machines as well, as winform app is going to run locally on the system.

    Approach 2: Using IronPython

    private void BtnJsonPy_Click(object sender, EventArgs e)
        {
            // 1. Create Engine
            var engine = Python.CreateEngine();
    
            //2. Provide script and arguments
            var script = @"C:\Users\simeh\source\HDFC\repos\SamplePy\SamplePy2\SamplePy2.py"; // provide full path
            var source = engine.CreateScriptSourceFromFile(script);
    
            // dummy parameters to send Python script 
            int x = 3;
            int y = 4;
    
            var argv = new List<string>();
            argv.Add("");
            argv.Add(x.ToString());
            argv.Add(y.ToString());
    
            engine.GetSysModule().SetVariable("argv", argv);
    
            //3. redirect output
            var eIO = engine.Runtime.IO;
    
            var errors = new MemoryStream();
            eIO.SetErrorOutput(errors, Encoding.Default);
    
            var results = new MemoryStream();
            eIO.SetOutput(results, Encoding.Default);
    
            //4. Execute script
            var scope = engine.CreateScope();
    
            var lib = new[]
            {
                "C:\\path\\SamplePy\\packages\\IronPython.2.7.9\\lib",
                "C:\\path\\SamplePy\\packages\\IronPython.2.7.9",
            };
    
            engine.SetSearchPaths(lib);
            engine.ExecuteFile(script, scope);
            //source.Execute(scope);
    
            //5. Display output
            string str(byte[] x1) => Encoding.Default.GetString(x1);
    
            Console.WriteLine("Errrors");
            Console.WriteLine(str(errors.ToArray()));
            Console.WriteLine();
            Console.WriteLine("Results");
            Console.WriteLine(str(results.ToArray()));
        }

    The issue I get here is that I keep getting errors like 'Json module error' or 'PIL module error'

    I read somewhere that PIL won't currently work with IronPython because it uses a native C library.

    The python script has ML logic and uses OCR etc., for image processing and hence requires PIL, which cannot be done in IronPython.

    So any better approach or ways or suggestions on how to call Python script from Winform C# application.

    Thanks In Advance!!!..

    Wednesday, July 3, 2019 10:47 AM

All replies

  • Hi,

    If you want to use "Using Inter-Process Communication" and contains "Python.exe", you can try to publish the app via Clickonce.

    If you want to handle the "IronPython" issue, maybe you can submit a new issue on github. Here is the link.

    https://github.com/IronLanguages/ironpython2/issues/new.

    Regards,

    Kyle


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, July 4, 2019 1:45 AM