I have a situation that I believe is relatively common. I want a script to import a module from another directory. My python project is laid out as follows:

~/project/
  |
  |---modules/
        |
        |---mod.py
  |---scripts/
        |---script.py

in script.py, I have from modules import mod. So my PYTHONPATH needs to be set to ~/project/ (something that PyCharm does automatically).

VSCode is a great editor, but everywhere else, it falls short, in my opinion. This is a perfect example of that.

I create a default launch.json file to "run the current file". A "cwd": "${fileDirname}" line has to be added to make things work like they do in PyCharm (FYI, a list of the built-in variables can be found here).

Debugging

For debugging (the "play" button on the sidebar, or the F5 key), the PYTHONPATH set in launch.json or your .env file takes effect. Note that in the .env file, you cannot use variables such as ${workspaceRoot}, but you can easily append or insert to the path by using the proper separator for your platform (; for Windows and : for everyone else).

Because I want to take advantage of that variable, I put this in my launch.json:

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

(Thanks to @someonr for the suggestion to use ${pathSeparator}.)

It appears that you can prepend/append to whatever is inherited from the environment (this is not true for settings.json; see below).

This will also work for the hotkey Ctrl+F5 (run without debugging).

For reference, here's the full file, which replicates what PyCharm does automatically:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "cwd": "${fileDirname}",
            "env": {"PYTHONPATH": "${workspaceFolder}${pathSeparator}${env:PYTHONPATH}"}
        }
    ]
}

Run in terminal

If I hit the "play" button that appears on the top right of the editor window (when a python file is the active tab), it will not work. This runs the current file in a terminal, which doesn't pay attention to launch.json at all. To make that work, you have to define PYTHONPATH in a settings.json file, by adding this:

    "terminal.integrated.env.osx": {"PYTHONPATH": "${workspaceFolder}"}

(Note there are different values for each platform.) If you've selected a python interpreter (e.g. from a virtual environment), you will already have a settings.json file in the .vscode directory. Mine looks like this:

{
    "python.pythonPath": "/Users/me/project/venv/bin/python3",
    "terminal.integrated.env.osx": {"PYTHONPATH": "${workspaceFolder}"}
}

You can't append or insert values into the inherited PYTHONPATH via the settings.json file. It will only take one string, and it will not parse separators. So even though you could get the value using ${env:PYTHONPATH}, you won't be able to do anything with it.

Moreover, you can't set the current working directory. Even though it would seem you could set it with "terminal.integrated.cwd": "${workspaceFolder}", it doesn't work. So if any of your scripts do anything with paths relative to their location in the tree, they won't work. The working directory will be your project root.

Note that any changes to the settings.json file will require that you exit the integrated terminal and restart it.

Linting

Nothing I do to launch.json regarding PYTHONPATH makes any difference to pylint, which will red-underline from modules import mod, despite the fact I can put the cursor on mod, hit F12, and the file opens. Snooping around linting settings, the defaults for mypy include --ignore-missing-imports. To replicate this behavior with pylint, add this to your settings.json:

    "python.linting.pylintArgs": [
        "--disable=F0401"
    ] 

Shame that we just have to work around this, but the autocomplete helps a lot when writing the import statements to begin with.

Conclusion

There are many layers to VSCode and it's hard to get things to work together. It seems multiple environments are floating around. In the end:

  1. I cannot "run in terminal" because I can't set the current working directory to be the path containing the current file.
  2. I cannot set PYTHONPATH for pylint as that runs in some environment different than the integrated terminal and whatever is controlled by launch.json, so I can only tell pylint to ignore import errors.
  3. Running with F5 works if you set PYTHONPATH either via an .env file or in launch.json
Answer from darda on Stack Overflow
🌐
Visual Studio Code
code.visualstudio.com › docs › python › environments
Python environments in VS Code
November 3, 2021 - PET finds environment managers by checking your PATH (for example, by looking for conda, pyenv, and poetry executables) and known installation locations, and then searches for environments managed by each of these environment managers.
Top answer
1 of 16
182

I have a situation that I believe is relatively common. I want a script to import a module from another directory. My python project is laid out as follows:

~/project/
  |
  |---modules/
        |
        |---mod.py
  |---scripts/
        |---script.py

in script.py, I have from modules import mod. So my PYTHONPATH needs to be set to ~/project/ (something that PyCharm does automatically).

VSCode is a great editor, but everywhere else, it falls short, in my opinion. This is a perfect example of that.

I create a default launch.json file to "run the current file". A "cwd": "${fileDirname}" line has to be added to make things work like they do in PyCharm (FYI, a list of the built-in variables can be found here).

Debugging

For debugging (the "play" button on the sidebar, or the F5 key), the PYTHONPATH set in launch.json or your .env file takes effect. Note that in the .env file, you cannot use variables such as ${workspaceRoot}, but you can easily append or insert to the path by using the proper separator for your platform (; for Windows and : for everyone else).

Because I want to take advantage of that variable, I put this in my launch.json:

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

(Thanks to @someonr for the suggestion to use ${pathSeparator}.)

It appears that you can prepend/append to whatever is inherited from the environment (this is not true for settings.json; see below).

This will also work for the hotkey Ctrl+F5 (run without debugging).

For reference, here's the full file, which replicates what PyCharm does automatically:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "cwd": "${fileDirname}",
            "env": {"PYTHONPATH": "${workspaceFolder}${pathSeparator}${env:PYTHONPATH}"}
        }
    ]
}

Run in terminal

If I hit the "play" button that appears on the top right of the editor window (when a python file is the active tab), it will not work. This runs the current file in a terminal, which doesn't pay attention to launch.json at all. To make that work, you have to define PYTHONPATH in a settings.json file, by adding this:

    "terminal.integrated.env.osx": {"PYTHONPATH": "${workspaceFolder}"}

(Note there are different values for each platform.) If you've selected a python interpreter (e.g. from a virtual environment), you will already have a settings.json file in the .vscode directory. Mine looks like this:

{
    "python.pythonPath": "/Users/me/project/venv/bin/python3",
    "terminal.integrated.env.osx": {"PYTHONPATH": "${workspaceFolder}"}
}

You can't append or insert values into the inherited PYTHONPATH via the settings.json file. It will only take one string, and it will not parse separators. So even though you could get the value using ${env:PYTHONPATH}, you won't be able to do anything with it.

Moreover, you can't set the current working directory. Even though it would seem you could set it with "terminal.integrated.cwd": "${workspaceFolder}", it doesn't work. So if any of your scripts do anything with paths relative to their location in the tree, they won't work. The working directory will be your project root.

Note that any changes to the settings.json file will require that you exit the integrated terminal and restart it.

Linting

Nothing I do to launch.json regarding PYTHONPATH makes any difference to pylint, which will red-underline from modules import mod, despite the fact I can put the cursor on mod, hit F12, and the file opens. Snooping around linting settings, the defaults for mypy include --ignore-missing-imports. To replicate this behavior with pylint, add this to your settings.json:

    "python.linting.pylintArgs": [
        "--disable=F0401"
    ] 

Shame that we just have to work around this, but the autocomplete helps a lot when writing the import statements to begin with.

Conclusion

There are many layers to VSCode and it's hard to get things to work together. It seems multiple environments are floating around. In the end:

  1. I cannot "run in terminal" because I can't set the current working directory to be the path containing the current file.
  2. I cannot set PYTHONPATH for pylint as that runs in some environment different than the integrated terminal and whatever is controlled by launch.json, so I can only tell pylint to ignore import errors.
  3. Running with F5 works if you set PYTHONPATH either via an .env file or in launch.json
2 of 16
60

The documentation is missing some important details.

Example

Suppose your project layout is like this

myproject/
    .vscode/
        settings.json
    .env
    src/
        a_module.py
    tests/
        test_a.py

Open the settings.json file and insert these lines

// On linux use "terminal.integrated.env.linux": {
"terminal.integrated.env.windows": {
    "PYTHONPATH": "${workspaceFolder}/src;${workspaceFolder}/tests"
},
// The next line can be omitted, unless you've modified the global default
"python.envFile": "${workspaceFolder}/.env",

Note that ${workspaceFolder} evaluates to myproject, it is not to the .vscode folder.

In the .env file enter this

PYTHONPATH=src;test
# Paths are relative to the workspace folder, so above is equivalent to
# WORKSPACE_FOLDER=C:/full/path/to/myproject
# PYTHONPATH=${WORKSPACE_FOLDER}/src;${WORKSPACE_FOLDER}/tests

Note that on all platforms, including Windows, the slashes in the path lean forward, like so /. Different paths are separated with a ; on Windows, on other platforms with a :.

Final step, restart VS Code.

This blog was helpful.

Discussions

How can I set up VSCode to recognize directory paths without manually changing the PYTHONPATH?
This is the best (and tbh the only correct way) to do it: https://stackoverflow.com/a/50193944/16773655 More on reddit.com
🌐 r/learnpython
11
3
October 25, 2021
Environment variables (PYTHONPATH) not read for testing in vscode
It should be able to modify environment variables (PYTHONPATH) according to .env, like in the previous version. It does not modify any environment variable during test runs through the VSCode Test tab. More on github.com
🌐 github.com
3
April 23, 2020
VS Code is resetting a valid PYTHONPATH from env to null
Issue Type: Bug Behaviour A valid value for the PYTHONPATH env variable (inherited from the shell from which vscode is launched) is reset to null in vscode. As a result pylance cannot find imports, and run/debug of the application does n... More on github.com
🌐 github.com
10
January 18, 2022
Explain once and for all how to set python.pythonPath using environment variables or remove this from docs
Environment data VS Code version: 1.44.0 Extension version (available under the Extensions sidebar): 2020.2.64397 OS and version: Linux x64 5.5.8-arch1-1 Python version: Virtual env python 2.7 Type of virtual environment used (N/A | venv... More on github.com
🌐 github.com
5
March 12, 2020
🌐
Donjayamanne
donjayamanne.github.io › pythonVSCodeDocs › docs › python-path
Python Path and Version | Python in Visual Studio Code
{ "python.pythonPath": "${workspaceRoot}/venv/bin/python" } Similar to the use of ${workspaceRoot}, environment variables could be used in configuring the path to the python interpreter.
🌐
Reddit
reddit.com › r/learnpython › how can i set up vscode to recognize directory paths without manually changing the pythonpath?
r/learnpython on Reddit: How can I set up VSCode to recognize directory paths without manually changing the PYTHONPATH?
October 25, 2021 -

I want to be able to have a separate dir for my test suite (which have imports from the source code). My source modules have imports that reference other files in the same directory and it works when I run that code, but when I try to run the test suite, VSCode can't find the modules. For some reason running the test suite works in PyCharm, and I've been trying to figure out the behavior in Pycharm so I could change the behavior accordingly in VSCode to no avail, and figured someone here would know. I'm trying to use VSCode instead of PyCharm because the project also has React/JS and I don't even know if PyCharm would support that (and I just like VSCode better in general... except for this annoying thing).

My directory structure is as follows:

app
|____init__.py
|__client
|__server
      |____init__.py
      |___.venv
      |___data
      |___lib
           |____init__.py
	       |___config.ini
	       |___config_reader.py
	       |___sql_connection.py  (imports config_reader and passes in 'lib/config.ini' to the reader function)
      |___tests
           |____init__.py
	       |___testconfig.ini
	       |___test_sql_connection.py (i try to import config_reader here but vscode will say that the module doesn't exist)

Does anyone have any advice?

EDIT: added that i do have init.py in my folders

🌐
Visual Studio Code
code.visualstudio.com › docs › python › settings-reference
Python settings reference
November 3, 2021 - The Python Environments extension provides environment and package management within the VS Code UI.
🌐
Redreamality's Blog
redreamality.com › blog › pythonpathvs-code
Setting PYTHONPATH Environment Variable: A Comprehensive Guide for All Platforms & VS Code Development
August 21, 2025 - This article will detail various methods for setting PYTHONPATH on Windows, macOS, and Linux systems, as well as several convenient and recommended ways to set module search paths for Python projects in Visual Studio Code (VS Code).
Find elsewhere
🌐
GitHub
github.com › microsoft › vscode-python › issues › 11351
Environment variables (PYTHONPATH) not read for testing in vscode · Issue #11351 · microsoft/vscode-python
April 23, 2020 - Modify the .env file PYTHONPATH variable to search for specified module created in step 1. Create a unit test (unittest) using the created module in a different folder (e.g. {workspaceFolder}/tests/) Run the test from the VSCode tab.
Author   jgangel
🌐
Bacancy Technology
bacancytechnology.com › qanda › python › set-the-root-directory-for-visual-studio-code-python-extension
Set Root Directory for Visual Studio Code Python Extension
1. Create a .env File: In the root of your project folder, create a .env file. This file allows you to set environment variables that VSCode will use during the development process.
🌐
GitHub
github.com › microsoft › vscode › issues › 141114
VS Code is resetting a valid PYTHONPATH from env to null · Issue #141114 · microsoft/vscode
January 18, 2022 - The core property of environment variables is that they are inherited from the parent process. Therefore, in the most natural and basic case, e.g. PYTHONPATH should be setup in the shell (or other parent process) before launching vscode, and then a python application can be run/debugged with no additional setup in vscode.
Author   MAFulator
🌐
Xebia
xebia.com › home › blog › setting python source folders in visual studio code
Setting Python Source Folders In Visual Studio Code | Xebia
June 14, 2022 - The .env file configures the Python environment used by the editor (for linting, testing, and IntelliSense), while settings.json ensures the integrated terminal and debugging sessions also recognize the source path.
🌐
Python Forum
python-forum.io › thread-40540.html
How to set PYTHONPATH in Visual Studio Code?
Hello! Belows are my dev environment, OS : Windows 11 python : Anaconda3 Apache Spark : 3.4.1 IDE : Visual Studio Code 1.18.1And I try to integrate apache spark pyspark into VS code. So I set the python path into settings.json file of vs code. '...
🌐
YouTube
youtube.com › watch
How to Add Python Path in Visual Studio Code (2023) - YouTube
In this video, I'll show you how you can add Python Path in Visual Studio Code. Before adding python path in vscode, first you need to know where python is i...
Published   November 19, 2023
🌐
GitHub
github.com › microsoft › vscode-python › issues › 10533
Explain once and for all how to set python.pythonPath using environment variables or remove this from docs · Issue #10533 · microsoft/vscode-python
March 12, 2020 - Environment data VS Code version: 1.44.0 Extension version (available under the Extensions sidebar): 2020.2.64397 OS and version: Linux x64 5.5.8-arch1-1 Python version: Virtual env python 2.7 Type of virtual environment used (N/A | venv...
Author   smac89
🌐
GitHub
github.com › microsoft › pylance-release › issues › 275
.env file with PYTHONPATH=... is not supported · Issue #275 · microsoft/pylance-release
August 24, 2020 - This works as expected if I disable pylance and use only Python vscode extension · More about expected behaviour: https://stackoverflow.com/questions/50089498/how-to-set-the-root-directory-for-visual-studio-code-python-extension · workspace structure: .env (which is at root of workspace) PYTHONPATH=source ·
Author   karolzlot
🌐
GitHub
github.com › microsoft › vscode-python › issues › 22824
Automatically set pythonpath correctly for default project setups · Issue #22824 · microsoft/vscode-python
February 1, 2024 - the current project directory "." should be part of the PYTHONPATH automatically and the necessary settings should be hidden and the user not to be forced to investigate the inner workings of vscode and the extension
Author   WolfgangFahl
Top answer
1 of 16
258
  • I have been using Visual Studio Code for a while now and found an another way to show virtual environments in Visual Studio Code.

  • Go to the parent folder in which venv is there through a command prompt.

  • Type code . and Enter. [It is working on both Windows and Linux for me.]

  • That should also show the virtual environments present in that folder.

Original Answer

I almost run into same problem every time I am working on Visual Studio Code using venv. I follow the below steps:

  1. Go to menu FilePreferencesSettings.

  2. Click on Workspace settings.

  3. Under Files:Association, in the JSON: Schemas section, you will find Edit in settings.json. Click on that.

  4. Update "python.defaultInterpreterPath": "Your_venv_path/bin/python" under workspace settings. (For Windows): Update "python.defaultInterpreterPath": "Your_venv_path\Scripts\python.exe" under workspace settings.

  5. Restart Visual Studio Code in case if it still doesn't show your venv.

Note: Use python.pythonPath instead of python.defaultInterpreterPath for older versions.

2 of 16
209

With a newer Visual Studio Code version it's quite simple.

Open Visual Studio Code in your project's folder.

Then open Python Terminal (Ctrl + Shift + P: Python: Create Terminal)

In the terminal:

python -m venv venv

You'll then see the following dialog:

Click Yes; and your venv is ready to go.

Open a new terminal within VSCode Ctrl + Shift + P and you'll see that venv is getting picked up; e.g.: (venv) ...

You can now instal packages as usual, e.g., pip install sklearn

To keep track of what is installed: pip freeze > requirements.txt


For the older versions of VSCode you may also need to do the following:

Then Python: Select Interpreter (via Ctrl + Shift + P)

And select the option (in my case towards the bottom)

Python 3.7 (venv) ./venv/Scripts/python.exe

If you see

Activate.ps1 is not digitally signed. You cannot run this script on the current system.

you'll need to do the following: https://stackoverflow.com/a/18713789/2705777

For more information see: Global, virtual, and conda environments

Installing Modules

Ctrl + Shift + P and Terminal: Create New Integrated Terminal

from the terminal

Windows: .\.venv\Scripts\activate

Linux: ./.venv/bin/activate

You can now instal packages as usual, e.g., pip install sklearn.

For Jupyter, you need to do more - Jupyter notebooks in Visual Studio Code does not use the active virtual environment