I am trying to run a python script from a Blazor WebApp using pythonnet. The python script is located in the project but the PyModule.Import call to the script throws an error saying the module can't be found.
Runtime.PythonDLL = @"C:\Users\homepc\AppData\Local\Programs\Python\Python312\python312.dll";
PythonEngine.Initialize();
using (Py.GIL())
{
PyObject pyScript = PyModule.Import(@"PythonCalls");
string result = pyScript.InvokeMethod("test");
}
How do I call a python script from a Blazor WebApp using pythonnet?
The error occurs because Py.Import follows Python’s module import system, which requires the module to be in Python’s sys.path
using (Py.GIL())
{
dynamic sys = Py.Import("sys");
sys.path.append(@"E:\TESTS\ConsoleApp15\ConsoleApp15"); // Adjust this path to project directory
dynamic pyScript = Py.Import("PythonCalls");
dynamic result = pyScript.test(); //using test method directly
Console.WriteLine(result);
}