简体   繁体   English

VS Code:相对导入(linting)

[英]VS Code: Relative imports (linting)

I have a multi-directory project.我有一个多目录项目。 I use absolute imports for each directory.我对每个目录都使用绝对导入。 For example,例如,

main_dir
|
| - sub_dir1
      |
      | - a.py (has say class A)
| - sub_dir2
      |
      | - b.py (imports class A. Syntax:  from subdir1.a import A)

When I run it in the terminal, from main_dir, it works fine.当我在终端中从 main_dir 运行它时,它工作正常。 However, this import gives me an "unresolved import 'differential_diagnosis.src.algorithm'Python(unresolved-import)" in VS code.但是,此导入在 VS 代码中为我提供了“未解析的导入 'differential_diagnosis.src.algorithm'Python(unresolved-import)”。 I do not know how to fix this.我不知道如何解决这个问题。

The biggest challenge I face because of this is that I cannot use the peek feature to look at what the member functions of class A do.因此,我面临的最大挑战是我无法使用 peek 功能查看 class A 的成员函数做了什么。

I have raised a similar ticket on GitHub Project .我在 GitHub项目上提出了类似的票。

You should place some code of what you are trying to do.您应该放置一些您正在尝试做的事情的代码。 What I can say is that Python looks for modules in the import search path.我能说的是 Python 在导入搜索路径中查找模块。 First it looks for built-in modules, Python looks in the sys.path variable which is initialized by the directory of the original script + PATH shell variable + some installation dependent default.首先它查找内置模块,Python 查找由原始脚本目录初始化的 sys.path 变量 + PATH shell 变量 + 一些依赖于安装的默认值。

See: https://docs.python.org/3/tutorial/modules.html参见: https://docs.python.org/3/tutorial/modules.html

To guarantee that your imports can be found, you can do:为了保证可以找到您的导入,您可以执行以下操作:

sys.path.append(pathname_to_module)

just before you import a module.就在您导入模块之前。

Try to add these codes in your python file:尝试在您的 python 文件中添加这些代码:

import sys
print(sys.path)

The interpreter only can search these paths to find modules.解释器只能搜索这些路径来查找模块。 Python will only automatically add the folder which contains the current python file to sys.path . Python 只会自动将包含当前 python 文件的文件夹添加到sys.path

'The path of 'sub_dir1' should not be found in sys.path . 'sub_dir1' 的路径不应在sys.path中找到。 You need to add these settings in launch.json file:您需要在 launch.json 文件中添加这些设置:

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

Then your workspace path will be added to sys.path .然后您的工作区路径将被添加到sys.path

If main_dir is the workspace folder, then you can change from subdir1.a import A to from main_dir.subdir1.a import A .如果main_dir是工作区文件夹,那么您可以from subdir1.a import A更改为from main_dir.subdir1.a import A

If not, it should be changed to from {workspaceName}.{folder}....main_dir.subdir1 import A , and you should add a __init__.py file in every folder to change the folder to a python package.如果不是,则应将其更改为from {workspaceName}.{folder}....main_dir.subdir1 import A ,并且应在每个文件夹中添加一个__init__.py文件以将文件夹更改为 python package。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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