pythonvisual-studio-codewindows-subsystem-for-linuxvisual-studio-debuggingvscode-debugger

From knowledge.schema.app_schema import APIResponse ModuleNotFoundError: No module named 'knowledge'


When I ran the debugger, the first error I encountered was 'ERROR: Error loading ASGI app. Could not import module "knowledge".'
So, I tried adding 'src' to the arguments.
However, the following error occurred:"

tpea90125130%  cd /mnt/c/Users/11009086/Documents/knowledge-base ; /usr/bin/env /home/martin_ubuntu/.pyenv/versions/3.11.4/bin/python /home/martin_ubuntu/.vscode-server/extensions
/ms-python.python-2024.4.1/python_files/lib/python/debugpy/adapter/../../debugpy/launcher 46779 -- -m uvicorn src.knowledge:create_app --port 8000 --reload 
INFO:     Will watch for changes in these directories: ['/mnt/c/Users/11009086/Documents/knowledge-base']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [37947] using WatchFiles
0.01s - Debugger warning: It seems that frozen modules are being used, which may
0.00s - make the debugger miss breakpoints. Please pass -Xfrozen_modules=off
0.00s - to python to disable frozen modules.
0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation.
0.01s - Debugger warning: It seems that frozen modules are being used, which may
0.00s - make the debugger miss breakpoints. Please pass -Xfrozen_modules=off
0.00s - to python to disable frozen modules.
0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation.
Process SpawnProcess-1:
Traceback (most recent call last):
  File "/home/martin_ubuntu/.pyenv/versions/3.11.4/lib/python3.11/multiprocessing/process.py", line 314, in _bootstrap
    self.run()
  File "/home/martin_ubuntu/.pyenv/versions/3.11.4/lib/python3.11/multiprocessing/process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "/home/martin_ubuntu/.pyenv/versions/3.11.4/lib/python3.11/site-packages/uvicorn/_subprocess.py", line 78, in subprocess_started
    target(sockets=sockets)
  File "/home/martin_ubuntu/.pyenv/versions/3.11.4/lib/python3.11/site-packages/uvicorn/server.py", line 65, in run
    return asyncio.run(self.serve(sockets=sockets))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/martin_ubuntu/.pyenv/versions/3.11.4/lib/python3.11/asyncio/runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "/home/martin_ubuntu/.pyenv/versions/3.11.4/lib/python3.11/asyncio/runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "uvloop/loop.pyx", line 1517, in uvloop.loop.Loop.run_until_complete
  File "/home/martin_ubuntu/.pyenv/versions/3.11.4/lib/python3.11/site-packages/uvicorn/server.py", line 69, in serve
    await self._serve(sockets)
  File "/home/martin_ubuntu/.pyenv/versions/3.11.4/lib/python3.11/site-packages/uvicorn/server.py", line 76, in _serve
    config.load()
  File "/home/martin_ubuntu/.pyenv/versions/3.11.4/lib/python3.11/site-packages/uvicorn/config.py", line 433, in load
    self.loaded_app = import_from_string(self.app)
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/martin_ubuntu/.pyenv/versions/3.11.4/lib/python3.11/site-packages/uvicorn/importer.py", line 22, in import_from_string
    raise exc from None
  File "/home/martin_ubuntu/.pyenv/versions/3.11.4/lib/python3.11/site-packages/uvicorn/importer.py", line 19, in import_from_string
    module = importlib.import_module(module_str)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/martin_ubuntu/.pyenv/versions/3.11.4/lib/python3.11/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1204, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 940, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/mnt/c/Users/11009086/Documents/knowledge-base/src/knowledge/__init__.py", line 14, in <module>
    from knowledge.schema.app_schema import APIResponse
ModuleNotFoundError: No module named 'knowledge'

my launch.json is below:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: FastAPI",
            "type": "python",
            "request": "launch",
            "module": "uvicorn",
            "args": [
                "src.knowledge:create_app",
                "--port",
                "8000",
                "--reload",
            ],
            "jinja": true,
            "justMyCode": true,
        }
    ]
}

enter image description here

How can i solve this?
I want to debug in wsl.
I run "poetry shell" and then "poetry run start" is ok.


Solution

  • I can reproduce the problem:

    enter image description here

    The information provided is not comprehensive, but this problem is a very classic python error, and of course it also involves some VSCode knowledge.

    Use this code to check what your workspace is and whether it is consistent with the running location of python (insert before the error line):

    import os print("Current working directory:", os.getcwd()) print("PYTHONPATH:", os.environ.get('PYTHONPATH'))

    I noticed that there is an init.py file in your knowledge directory. Therefore, structurally it has met the conditions for being regarded as a module by python.

    The error report you shared shows that python does not regard knowledge as a module at the first level (even if its structure is correct), so I judge that this is a problem where the workspace is inconsistent with the running location of python. Please first ensure that pythonpath and working directory are consistent:

    {
        "version": "0.2.0",
        "configurations": [
          {
            "name": "Python: Current File",
            "type": "debugpy",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "env": {
              "PYTHONPATH": "${workspaceFolder}"
            }
          }
        ]
      }
      
    

    By the way, in this situation, we need to start from src because workspace is in the root directory. You should make sure there is a __init__.py file in the src folder(For the python to find the module, you don't need to write anything in it.). the code in knowledge\__init__.py should be like this:

    from src.knowledge.schema.app_schema import APIResponse