是否可以在 vscode 中添加 python 的项目引用?

Is there a possibility to add a project reference for python in vscode?

对于 C# 项目,有一种简单的方法可以在解决方案中引用其他项目。现在,我想知道 python 项目中是否有类似的方法。

比方说,我有一个这样的文件夹结构:

Base_directory/Project/SomeFile.py
Base_directory/Project_UnitTests/SomeFileTests.py

SomeFile.py

class SomeClass:
    pass

对于单元测试,如果我使用相对导入,它工作正常。 SomeFileTests.py:

from ..Project.SomeFile import SomeClass
#...    

但是,我想要实现的是拥有以下代码:

from Project.SomeFile import SomeClass
#...

但是为此,我显然需要引用 Project 文件夹。我知道,我可以直接在代码中使用 python-path 变量,但是我需要在单元测试代码中找到该文件夹​​的路径 - 我不认为它属于那里。

有没有一种优雅的方法可以使用 Python 在 Visual Studio 代码中添加项目引用?

您可以通过 terminal.integrated.env.* and/or 在 .env 文件中修改 PYTHONPATH。可以参考官方文档 here.

The PYTHONPATH environment variable specifies additional locations where the Python interpreter should look for modules. In VS Code, PYTHONPATH can be set through the terminal settings (terminal.integrated.env.*) and/or within an .env file.

但它们有些不同:

When the terminal settings are used, PYTHONPATH affects any tools that are run within the terminal by a user, as well as any action the extension performs for a user that is routed through the terminal such as debugging. However, in this case when the extension is performing an action that isn't routed through the terminal, such as the use of a linter or formatter, then this setting will not have an effect on module look-up.

When PYTHONPATH is set using an .env file, it will affect anything the extension does on your behalf and actions performed by the debugger, but it will not affect tools run in the terminal.

If needed, you can set PYTHONPATH using both methods.

完全符合您的目标:

An example of when to use PYTHONPATH would be if you have source code in a src folder and tests in a tests folder. When running tests, however, those tests can't normally access modules in src unless you hard-code relative paths.

To solve this problem, you could add the path to src to PYTHONPATH by creating an .env file within your VS Code workspace.

PYTHONPATH=src

Then set python.envFile in your settings.json file to point to the .env file you just created. For example, if the .env file was in your workspace root, your settings.json would be set as shown:

"python.envFile": "${workspaceFolder}/.env"