Calling Python from C# using Pythonnet throws import error
Question:
I have a use case where I want to be able to call a function which is written in Python from my C# code base. When I make a call to this function I want to be able to pass C# types(custom classes) to Python function and for that I was exploring pythonnet.
Python project has a following sample structure –
main.py
service1.py
main.py has the main function which calls the methods exposed by service1.py –
from Service1 import MyService1
def Run(a, b):
service1 = MyService1()
service1.method(a, b)
Now from C# side when I try to execute the Python it is throwing error –
Python.Runtime.PythonException: ‘No module named ‘Service1”
C# code –
Runtime.PythonDLL = @"C:Program FilesPython39Python39.dll";
PythonEngine.Initialize();
using (Py.GIL())
{
using (var scope = Py.CreateScope())
{
scope.Exec(File.ReadAllText(@"..Pythonmain.py"));
}
}
How do I need to import the required classes correctly?
Answers:
I was running into this issue because my Python scripts were not part of the build folder. I had to ensure that the required Python files are part of the build folder on the successful build of the solution.
To make a file part of your build folder you will need to –
Right click on file in VS -> Properties -> Copy To Output directory -> select Copy Always or Copy if newer.
Alternatively, you can do this from .csproj file as well.
I have a use case where I want to be able to call a function which is written in Python from my C# code base. When I make a call to this function I want to be able to pass C# types(custom classes) to Python function and for that I was exploring pythonnet.
Python project has a following sample structure –
main.py
service1.py
main.py has the main function which calls the methods exposed by service1.py –
from Service1 import MyService1
def Run(a, b):
service1 = MyService1()
service1.method(a, b)
Now from C# side when I try to execute the Python it is throwing error –
Python.Runtime.PythonException: ‘No module named ‘Service1”
C# code –
Runtime.PythonDLL = @"C:Program FilesPython39Python39.dll";
PythonEngine.Initialize();
using (Py.GIL())
{
using (var scope = Py.CreateScope())
{
scope.Exec(File.ReadAllText(@"..Pythonmain.py"));
}
}
How do I need to import the required classes correctly?
I was running into this issue because my Python scripts were not part of the build folder. I had to ensure that the required Python files are part of the build folder on the successful build of the solution.
To make a file part of your build folder you will need to –
Right click on file in VS -> Properties -> Copy To Output directory -> select Copy Always or Copy if newer.
Alternatively, you can do this from .csproj file as well.