I am working in a .NET core console application and using Python net to call python scripts from within the C#, and I would like to create a helper script that takes care of calling the Python script since we need to set some variables, initialize the interpreter, navigate to the system path, etc.
For those not familiar with Python net it imports a python module into the C# and then you can use it just like it is a C# class and you can call functions within the module, pass parameters to them, and receive the result in the C#.
The problem I am having is I need to pass multiple parameters to these functions, so I am trying to use the params keyword for the first time, but it seems that it is passing an array as a single parameter rather than passing the parameters themselves to the python script.
public dynamic ExecutePythonFunction(string moduleName, string functionName, params object[] args)
{
String fileDirectoryPath = CommonVariables.PythonScriptsDirectoryPath;
using (Py.GIL())
{
dynamic sys = Py.Import("sys");
sys.path.append(fileDirectoryPath);
dynamic module = Py.Import(moduleName);
dynamic function = module.GetAttr(functionName);
return function(args);
}
}
// Example usage
ExecutePythonFunction("face_detection", "process_video_from_file", videoPath, outputVideoPath);
In this example the python script process_video_from_file in the face_detection module takes two parameters: videoPath, outputVideoPath
I have been working with ChatGPT 4 on this, I tried using function.call(args) but had the same issue. Also, function.Invoke(args) and function.InvokeMethod(args) but neither of those are valid. Casting to an object did not work function((object)args), or using * before args function(args) function((object)args) due to syntax error. Probably I could rewrite my python scripts to take an array as the parameters as a workaround but that is less than ideal.
The end goal is simply to be able to pass multiple parameters to the python function without having to write all of that out each time
Beefman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.