Marking a directory as sources root equivalent in Visual Studio Code for Python

In PyCharm you have that nice easy right click shortcut to mark a folder as sources root. But in VS code things you don’t have that simple setup. If you are coming from ModuleNotFoundError: No module named you should have known why you need this.

You can easyliy resolved by adding below setting to the VS code settingss.json . Assume that the local modules that you are importing is from src folder. This has been tested with Conda env and unit test in terminal. Python language server is set to Pylance. All other setting remain untouched.

1
2
3
4
5
6
7
8
9
"terminal.integrated.env.osx": {
"PYTHONPATH": "${workspaceFolder}/src",
},
"terminal.integrated.env.linux": {
"PYTHONPATH": "${workspaceFolder}/src",
},
"terminal.integrated.env.windows": {
"PYTHONPATH": "${workspaceFolder}/src",
},

If you are calling the py file from terminal directly, you can also append the src path to PYTHONPATH so you won’t get import error.

1
export PYTHONPATH=$PYTHONPATH:$(git rev-parse --show-toplevel)/src
AWS Lightsail Wireguard Unable to access interface: Protocol not supported easy fix React Native Screens swipe flickering or white edge in dark mode fix

Comments