Solve the problem that vscode cannot find the Python custom module, and reports an error No module named 'xxx'

In the process of learning python recently, the author put the project that ran successfully in pycharm into vscode, and found some errors, such as not being able to find the author's custom module, and referred to some sayings and methods, and now record the solution here.

foreword

The reason why vscode cannot find the custom module is related to its PYTHONPATH . The author's directory structure is shown in the figure:

After practice, it is found that if do_mysql.py is at the same level as testDatas, the above statement can be imported successfully, and if do_mysql.py is imported at the same level as do_excel.py: import do_excel, it can also be successfully imported.

But the import module: from testDatas import filePath, error No module named 'testDatas'

Goal: reference filePath.py() in do_mysql.py

Since the error is quoted, it means that testDatas cannot be found in the current file structure, we can import sys, output sys.path, and check the current paths:

It can be seen that only the first one of these paths is related to the author's project, and it is the directory of do_mysql.py, so testDatas cannot be found. Therefore, if you want to introduce filePath.py, you need to find testDatas first, so there are two methods:

Solution

method one

Append the path to sys.path as an absolute path ("D:\pro\interfaceTest" is the author's project path):

import sys
sys.path.append("D:\pro\interfaceTest")

Append the path to sys.path as a relative path :

import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../testDatas'))

Add to setting.json (if there is no such file, you can add it yourself) under .vscode (a hidden directory) of the current project:

{
    "python.analysis.extraPaths": ["./testDatas"]
}

Click the run button in the upper right corner to take effect!

Method Two

Although the first method can take effect, it is really annoying to have to do this for each file. We can configure the path of the module to facilitate the next import.

First add "env": {"PYTHONPATH": "${workspaceRoot}"} to launch.json under .vscode:

{
  "version": "0.2.0",
  "configurations": [
    {
      // 省略其他
      "env": {"PYTHONPATH": "${workspaceRoot}"}
    }
  ]
}

Add in settings.json under .vscode:

{
  // 省略其他
  "terminal.integrated.env.windows": {
    "PYTHONPATH": "${workspaceFolder};${env:PYTHONPATH}"
  }
}

Save the above file, press F5 in do_mysql.py, and it will take effect! ! ! But click the run button in the upper right corner, still report No module named 'testDatas', it doesn't matter, just restart vscode, run it again, it will be successful!

verify again

At this point we can output sys.path to see:

It is found that the interfaceTest directory has been loaded!

Guess you like

Origin blog.csdn.net/sxww_zyt/article/details/129487582