0

Apparently, python interpreter is unable to find location of the hello_world.py script which I'm trying to run by using python.NET. I think I've set the environment variables correctly. Even though I've added the MyScripts path to the PYTHONPATH environment variable, Python.Runtime.PythonException: No module named 'hello_world' is thrown which confuses me. Could anyone please indicate what I'm missing? I will also add the python script cause I'm not sure if the problem lies there.

Versions:

python.Net 3.0.1 64-bit (Installed from NuGet using dotnet CLI)

python 3.8 64-bit

dotnet 6.0

These SO answers[1, 2] were helpful but I'm still unable to resolve my issue.

using System;
using Python.Runtime;

namespace  HelloWorld
{
    class  Program 
    {
        static void Main(string[] args) 
        {
            string user = "user1";

            var PYTHONNET_PYDLL = @$"C:\Users\{user}\AppData\Local\Programs\Python\Python38\python38.dll";
            
            var pathToPythonnet = @$"C:\Users\{user}\AppData\Local\Programs\Python\Python38\Lib\site-packages";
            
            var pathToScript = @$"C:\Users\{user}\MyScripts";
            
            var pathToPython = @$"C:\Users\{user}\AppData\Local\Programs\Python\Python38\";

            var paths = pathToPython + ";" + pathToPythonnet + ";" + pathToScript + ";" +  Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine); 

            Environment.SetEnvironmentVariable("PYTHONNET_PYDLL",  PYTHONNET_PYDLL, EnvironmentVariableTarget.Process); 
            Environment.SetEnvironmentVariable("PYTHONHOME", pathToPython, EnvironmentVariableTarget.Process);
            Environment.SetEnvironmentVariable("PYTHONPATH", paths, EnvironmentVariableTarget.Process );

            PythonEngine.Initialize();
            using (Py.GIL())
            {
                dynamic np = Py.Import("numpy");
                Console.WriteLine(np.cos(np.pi * 2 )); // this works

                dynamic helloPy = Py.Import("hello_world"); // TODO: module not found 
                dynamic result = helloPy.hello_world();
                Console.WriteLine($"Python says: {result}");
            }
        }
    }

}

hello_world.py file location is C:\Users\{user}\MyScripts\hello_world.py. And the script looks like this

def hello_world():
 print("script is running....")
 return "Hello World!"

Error thrown on running dotnet run CLI

1.0
Unhandled exception. Python.Runtime.PythonException: No module named 'hello_world'
   at Python.Runtime.PythonException.ThrowLastAsClrException()
   at Python.Runtime.NewReferenceExtensions.BorrowOrThrow(NewReference& reference)
   at Python.Runtime.PyModule.Import(String name)
   at Python.Runtime.Py.Import(String name)
   at HelloWorld.Program.Main(String[] args)

0 Answers0