pythonpythonpath

add a python path to a module in visual studio code


I'm having difficulty specifying python path containing modules/packages in another directory or even folder of the same project. When I try to import I get the error:

ModuleNotFoundError: No module named 'perception'

In Spyder this is simply done using the UI to select an additional pythonpath that python will look in, but I am unable to do so in VSC.

Note I have tried following other answers on editing the settings.json files, and .env files but the problem still persists.

The only solution I have is to use sys.path.append() in every script which is not what I am looking for.

As an example my settings.json file is:

{
    "terminal.integrated.env.osx": {
        "PYTHONPATH": "pathtoprojectfolder"
    },
    "python.envFile": "${workspaceFolder}/.env",
    "jupyter.interactiveWindowMode": "perFile",
    "python.terminal.executeInFileDir": true,
    "terminal.integrated.inheritEnv": true,
    "jupyter.themeMatplotlibPlots": true,
    "window.zoomLevel": 2,
    "python.condaPath": "path_to_conda_python",
    "python.defaultInterpreterPath": "path_to_conda_python",
}

Solution

  • Instructions for MacOS only.

    Adding .env files and navigating the setting json files is not as intuitive and simple as adding an additional python path in Spyder. However, this worked for me on VSC:

    1. create a .env file in the project folder.
    2. add the full path that you want to add to PYTHONPATH as such: PYTHONPATH=/Users/../projectFolder:/Users/.../AnotherProjectFolder

    ** crucially you must use the appropriate separator between paths, on Mac you must use ':', otherwise the paths will not be added.

    1. go to to Code->preferences->settings and search for "terminal.integrated.osx". click edit "settings.json"

    2. add to the json settings

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

    As an example you might to have settings.json showing the following:

    {
        "python.envFile": "${workspaceFolder}/.env",
        "jupyter.interactiveWindowMode": "perFile", 
        "python.terminal.executeInFileDir": true,
    }
    

    Quite an involved process to just add a path, but I like the ability to run Jupyter notebooks in VSC which Spyder doesn't have in the standalone installers yet.

    This page has the information required: https://code.visualstudio.com/docs/python/environments#_environment-variable-definitions-file