pythonnet: cannot find class in module

Environment

  • Pythonnet version:3.0.0
  • Python version:3.8.3
  • Operating System:windows10
  • .NET Runtime:dotnet core 5.0

Details

  • get error:
Traceback (most recent call last):
  File ".\test.py", line 15, in <module>
    from MyApp  import Class1
ImportError: cannot import name 'Class1' from 'MyApp' (unknown location)
  • my config file:
{
  "runtimeOptions": {
    "tfm": "netcoreapp5.0",
    "framework": {
      "name": "Microsoft.NETCore.App",
      "version": "5.0.2"
    }
  }
}
  • python code
    from clr_loader import get_coreclr
    from pythonnet import set_runtime
    
    rt = get_coreclr("D:\\test\\BotTest\\test.runtimeconfig.json")
    set_runtime(rt)
    
    import clr
    import sys
    import System
    sys.path.append("D:\\test\\BotTest\\MyApp\\bin\\Debug\\net5.0")
    clr.FindAssembly("MyApp")
    
    clr.AddReference("MyApp")
    from System  import Console
    from MyApp  import Class1
  • c# code
using System;

namespace MyApp
{
    public class Class1
    {
        public static void f(){
            Console.WriteLine("zzz");
        }
    }
}
  • It seems that latest version does not work well for dotnet core

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 15 (4 by maintainers)

Most upvoted comments

Hi everyone, i ran into this exception and found this post answering the question, hope it helps in my case, i have developed both programs python and dotnet in separate directories and imported the dotnet bin into python’s app dir and it works fine so far https://stackoverflow.com/a/63728744/12821529

Hmm… The issue is that Python just “imports” the MyApp directory as a “namespace package”, not sure why. If you rename it or run your program from a different path, it works just fine.