首页 > 解决方案 > 如何在 VScode 中正确设置 PYTHONPATH 环境

问题描述

项目结构如下

- a.py
- unittest
   - test_a.py

py

class A():
    def function_a(self):
        return 'function_a'

test_a.py

from a import A

class TestA():
    def test_a(self):
        assert A().function_a() == 'function_a'

当我使用终端和set PATHONPATH=//<my-project-folder>时,可以通过pytest. 但是,当我尝试在 VScode 中调试它时,它一直在抛出No module named a.

https://code.visualstudio.com/docs/python/environments#_environment-variable-definitions-file

我已经尝试过这种方式并将一个.env放在我的项目文件夹中。

.env

PYTHONPATH=C:\\Repos\\test-project

(我在有和没有逃跑的情况下都这样做了,无论如何它都没有用。)

.vscode/setting.json

{
    "python.pythonPath": "C:\\Python27\\python.exe",
    "python.testing.pytestArgs": [
        "unittest"
    ],
    "python.testing.unittestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.testing.pytestEnabled": true,
    "python.envFile": "${workspaceFolder}/.env",
}

标签: python-2.7visual-studio-codepythonpath

解决方案


要找出PYTHONPATH环境变量的值是什么,请使用以下test_a.py文件

import os

def test_PYTHONPATH():
  assert os.environ.get('PYTHONPATH') == "XX"

我已经在 Windows 上使用 Python 3.6 对其进行了测试。

在我的测试中,我.env在工作区根文件夹中设置了一个内容

PYTHONPATH=C:\Projects\test-project\

运行测试给出了一个断言错误,并显示 的值PYTHONPATH是操作系统定义的值。

启动终端并PYTHONPATH从全局环境变量中删除并使用 as 参数从此终端启动 VSCC:\Projects\test-project\打开项目,现在测试失败,但显示文件PYTHONPATH中定义的正确.env

我得到的结论是操作系统环境变量(在 Windows 上)会覆盖 VSC 设置的任何环境变量。如果这是正确的,您不能像文档中显示的那样扩展环境变量

PYTHONPATH=${PROJ_DIR}:${PYTHONPATH}

这应该在 VSC 或 VSC-python 扩展中作为错误提交。

在 VSC 中定义的任何内容都应该覆盖任何操作系统环境变量并能够使用任何操作系统环境变量。


推荐阅读