pythonc#azure-functionspython.net

Using Python.NET in a C# Azure function


We have developed all our functions using C#, and would like to continue doing so. But we have a parsing library written in Python that we'd like to use. We've therefor looked at Python.NET (pythonnet) to execute the Python code within our C# process.

Everything works if I run it locally using a vanilla C# Console app. But when I move the same code to a Azure function project it fails (even locally).

Runtime.PythonDLL = @"python310.dll";
PythonEngine.Initialize();

// This line fails with "No module named 'wmbus2json'"
var parser = Py.Import(@"wmbus2json"); 

It seams the runtime cannot find the Python files although they are in the bin directory. We are running our Azure Function using .net 6 Isolated

Thanks for any help


Solution

  • The following works when running locally.

        Runtime.PythonDLL = @"python310.dll";
        PythonEngine.Initialize();
        using var _ = Py.GIL();
        string scriptPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "wmbus2json.py");
        dynamic sys = Py.Import("sys");
        sys.path.append(Path.GetDirectoryName(scriptPath));
        PyObject pythonLib = Py.Import(Path.GetFileNameWithoutExtension(scriptPath));