vscode imports custom package display: ModuleNotFoundError: No module named ' *** '

If you don’t want to read the problem description, you can go directly to the solution.

Problem Description

vscode will have some problems in importing custom packages. The next project from github cannot be run, and ModuleNotFoundError: No module named '***' is displayed.

For example, there is the following project, the project name is experience, and there is a parent package underneath. The parent package contains parent_main.py and the child sub-package, and the child package contains child_main.py

experience
|----parent
|------parent_main.py
|------child
|----------child_main.py

parent_main.py

def parent_main_func():
    print('parent_main_func')
if __name__ == '__main__':
    import sys
	# 查看环境变量
    for a_path in sys.path:
        print(a_path)

vscode running results

c:\Project\experience\parent
C:\Applications\Anaconda\envs\pytorch\python39.zip
C:\Applications\Anaconda\envs\pytorch\DLLs
C:\Applications\Anaconda\envs\pytorch\lib
C:\Applications\Anaconda\envs\pytorch
C:\Users\Powerful\AppData\Roaming\Python\Python39\site-packages
C:\Applications\Anaconda\envs\pytorch\lib\site-packages
C:\Applications\Anaconda\envs\pytorch\lib\site-packages\pyeeg-0.4.4-py3.9.egg

The most critical root directory of this project is missingC:\Project\experience

child_main.py

if __name__ == "__main__":
    from parent.parent_main import parent_main_func
    parent_main_func()

vscode running results
Error: ModuleNotFoundError: No module named 'parent'


solution:

in vscodesetting.jsonThe settings inside automatically add the project's root directory to the environment variables.

1. Open setting.json. In the settings in the lower left corner

Insert image description here

2.Pull down

Insert image description here

3.Add a line of code below pythonPath (copy and paste directly, no need to change!)

Insert image description here

"terminal.integrated.env.windows": {
    
    "PYTHONPATH":"${workspaceFolder};${env:PYTHONPATH}"},

This statement does not work for Linux systems, it will have multiple semicolons at the end. Should be changed to:

"terminal.integrated.env.windows": {
    
    "PYTHONPATH":"${workspaceFolder}:${env:PYTHONPATH}"},

Guess you like

Origin blog.csdn.net/ittongyuan/article/details/131362782