简体   繁体   中英

Visual Studio Code tells me it can't import python module, yet it runs the code

I am running a script in many folders and subfolders, the structure is kinda confusing but it basically is like:

src/
  controllers/
     __init__.py
     a.py
     b.py
   models/
     __init__.py
     c.py
   __init__.py
   main.py

The ^^^ is supposed to be the red error underline, main.py looks something like:

from controllers import a
^^^^
import models.c
^^^^^^

a.py:

import models.c
^^^^^^

I tried both, from and regular import, because maybe only one is bugged, but no, in VSC at every place I import like this, it tells me unable to import [directory] (it still runs from VSC and from the terminal via python3 main.py )

Things I tried

  • Restarting VSC
  • Rebooting my PC
  • Changing stuff in __init_.py (yet nothing systematic, just playing around)

Is this a visual studio code issue, is it bad importing? Should I put stuff into __init__.py ? Can I supress this issue or fix it somehow else?

When importing modules in other folders, VSCode searches for files from the parent folder of the currently running file by default. For example: " import models.c " in " a.py ", the parent folder " controllers/ " of " a.py " does not have " models ", so the terminal displays a warning.

When I removed the same level file " __init__.py " of " main.py ", the terminal did not display errors and warnings:

在此处输入图像描述

For " a.py ", I added the following settings in " launch.json ", which adds the project folder path to the system path for VSCode to find:

"env": {
                "PYTHONPATH": "${workspaceFolder}"
            }

Debug a.py:

在此处输入图像描述

Update:

On the premise that the code can run, I use the following settings to turn off the " import-error " displayed by Pylint:

"python.linting.pylintArgs": ["--disable=E0401"],

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM