I can’t call python function with c# pythonnet

I wanted to use Python for the backend and design for C# I tried many things but the error did not get fixed
my c# code:

using Python.Runtime;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {


           
                string pythonPath = @"C:\Users\egeca\AppData\Local\Programs\Python\Python39";

                Environment.SetEnvironmentVariable("PYTHONNET_PYDLL", @"C:\Users\egeca\AppData\Local\Programs\Python\Python39\python39.dll");

                Environment.SetEnvironmentVariable("PYTHONHOME", pythonPath, EnvironmentVariableTarget.Process);
                Environment.SetEnvironmentVariable("PYTHONPATH", pythonPath + @"\Lib\site-packages\pythonnet\runtime", EnvironmentVariableTarget.Process);

                

                
                PythonEngine.Initialize();

                using (Py.GIL())
                {
                    dynamic pythonScript = Py.Import("C:/Users/egeca/Desktop/Tenis Kortu/deneme.py");
                    dynamic a = pythonScript.denemee();

                    MessageBox.Show(a.ToString());
                }

                PythonEngine.Shutdown();
            
            
        }
    }
}

my python code:



def denemee():
    a = "deneme"
    return a

My C# code cannot find Python file location I looked in the forums but this problem was not solved
error code: Python.Runtime.PythonException: 'No module named 'C:/Users/egeca/Desktop/Tenis Kortu/deneme''

In some forums they said I should add this part to my code but it didnt work

string pythonPath = @"C:\Users\egeca\AppData\Local\Programs\Python\Python39";

Environment.SetEnvironmentVariable("PYTHONNET_PYDLL", @"C:\Users\egeca\AppData\Local\Programs\Python\Python39\python39.dll");

Environment.SetEnvironmentVariable("PYTHONHOME", pythonPath, EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("PYTHONPATH", pythonPath + @"\Lib\site-packages\pythonnet\runtime", EnvironmentVariableTarget.Process);

Leave a Comment