How to set the PYTHONPATH for your VirualEnv in Windows

VSCode keeps telling me “ImportError: No module named xxx”. Why? because I’m trying to run a code from a sub-folder and the module is in the parent directory. How to fix this? Well easy, add the parent directory to your PYTHONPATH. But how?

There are some options out there, for example adding the absolute address to a file named .env and placing it in your root folder.

Or adding the pythonpath to your launch.json file.

But this is how I did it:

Open the activate.ps1 file in your venv/scrips/activate.ps1 and add the following to the “deactivate” function:

if (Test-Path env:_OLD_VIRTUAL_PATH) {
copy-item env:_OLD_VIRTUAL_PATH env:PATH
remove-item env:_OLD_VIRTUAL_PATH
}

And add this to the end of the file:

if (Test-Path env:PYTHONPATH) {
copy-item env:PYTHONPATH env:_OLD_PYTHON_PATH
}
$env:PYTHONPATH = "$(Resolve-Path "$env:VIRTUAL_ENV\..");$env:PYTHONPATH"

Comments