【问题标题】:VS Code Python autocomplete doesn't work in parallel test directory structureVS Code Python 自动完成功能在并行测试目录结构中不起作用
【发布时间】:2022-01-16 00:25:36
【问题描述】:

我正在将 vs 代码用于 python 项目。该项目的 python 源代码和测试代码目录是分开的,但它们的结构彼此平行。我能够在命令行和 vs 代码中运行测试而不会出现问题。尽管如此,在修改test_file.py 中的代码时,vs 代码的自动完成功能并没有看到./src/main/python 中的模块并显示导入错误“无法解析导入模块名称”。

期待

尽管 src 和测试目录结构相互平行,但自动更正可以在测试目录中工作。

注意:如果我将 test 目录结构更改为不再与 src 目录结构平行,问题就会消失。

对此的任何帮助将不胜感激。如果需要,我很乐意提供更多信息。


示例测试代码

test_file.py

from pytest import mark

# This is where we have an error in the code editor despite
# this running fine.
#
# Import module_A.mocule_1.file could not be resolved
from module_A.module_1.file import handler

@mark.unit_test
class Handler_tests:
    def test_happy_path(self):
        handler(None)

我在项目根目录有一个 .env,其中包括

.env

PYTHONPATH=./src/main/python:./src/test/python

项目目录结构

// note, some non-python code directories/files exist but are omitted
<proj_root>
├──README.md
├──.env
└──src
    ├── main
    │   └── python
    │       └── module_A
    │           ├── __init__.py
    │           └── module_1
    │               ├── __init__.py
    │               └── file.py
    └── test
        └── python
            ├── conftest.py
            └── module_A
                ├── __init__.py
                └── module_1 
                     └── test_file.py  

环境信息

VS 代码

Version: 1.63.0-insider (Universal)
Commit: bedf867b5b02c1c800fbaf4d6ce09cefbafa1592
Date: 2021-11-18T05:17:00.890Z (3 wks ago)
Electron: 13.5.2
Chromium: 91.0.4472.164
Node.js: 14.16.0
V8: 9.1.269.39-electron.0
OS: Darwin arm64 21.1.0

皮兰斯

v2021.12.2-pre.1

【问题讨论】:

    标签: python visual-studio-code


    【解决方案1】:
    PYTHONPATH=src/main/python
    

    您可以在代码中验证 PYTHONPATH (sys.path)。

    【讨论】:

    • 非常感谢@Steven-MSFT。这是对 python 的基本原理,以及它对 sys.path 的使用,还是这是 VS Code 特有的原因?
    • PYTHONPATH可以增加模块文件的默认搜索路径,不同的IDEA对PYTHONPATH的修改方法不同。
    猜你喜欢
    • 2018-11-04
    • 2019-11-21
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 2021-10-30
    • 2020-01-10
    相关资源
    最近更新 更多