[Python] How can I call python script in c#?

Discussão em 'Python' iniciado por Stack, Março 8, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on a project which needs to call python script in c#. The fact is that I'm familiar with python, but not c#, not at all.

    As I have learnt, there are basically two options: Iron and Python.net, you can check it out here https://www.youtube.com/watch?v=oG5mmElsWJM&lc=UgzwcXvIteCqTjmHl2N4AaABAg.9Ls9q7VkDdc9MCYIPfOW0d. I'm struggling with python.net now. I've tried to call a simple multiply function (e.g. a * b), works perfect. But when I turned to image data, there pops up an error called "The type initializer for 'Delegates' threw an exception."

    The python script I used is:

    import cv2
    import numpy as np

    def binarise(image):
    ret, img_output = cv2.threshold(image,100,255,cv2.THRESH_BINARY)
    return img_output


    The c# I tried is:

    if (greyImage1 != null)
    {
    try
    {
    var pythonPath = @"C:\Users\Admin\anaconda3";

    Environment.SetEnvironmentVariable("PATH", $@"{pythonPath};" + Environment.GetEnvironmentVariable("PATH"));
    Environment.SetEnvironmentVariable("PYTHONHOME", pythonPath);
    Environment.SetEnvironmentVariable("PYTHONPATH ", $@"{pythonPath}\Lib");

    string scriptFile = "myfunction.py";
    string pythonCode = "";
    using (var streamReader = new StreamReader(scriptFile, Encoding.UTF8))
    {
    pythonCode = streamReader.ReadToEnd();
    }

    using (Py.GIL())
    {
    var scope = Py.CreateScope();
    scope.Exec(pythonCode);
    greyImage1 = (scope as dynamic).binarise(greyImage1);
    pictureBox1.Image = (System.Drawing.Image)greyImage1;
    this.Cursor = Cursors.Default;
    }
    }
    catch (Exception ex) { messageL.Text = ex.Message; }
    }


    Anyone got any ideas? Appreciate your time and help.

    Continue reading...

Compartilhe esta Página