I am trying to do an import in python from one directory level up.
import sys
sys.path.append(\'..\')
from cn_modules import exception
I g
In my case, it's nothing to do with
"env": {"PYTHONPATH": "${workspaceRoot}"}
Here is my folder/module structure:
/Dev/csproj/deploy/test.py
/Dev/csproj/util/utils.py
and in test.py, it imports the utils function
import sys
sys.path.append('../')
from util.utils import get_keyvault_secret
It has no issue if I run test.py in terminal folder /Dev/csproj/deploy/.
But if I want to debug test.py in VSCode (under workspaceRoot), I got the exception of "ModuleNotFoundError"
To fix it, I add this to my debug configuration launch.json
"cwd": "${workspaceRoot}\\Dev\\csproj\\deploy",
I have had the same problem, in my case it was caused by the current directory of the vscode debug process being different to the directory the script was in. It is helpful to do a
print('cwd is %s' %(os.getcwd()))
Just before your sys.path.append
and your imports. What happened with me is that the running environment cwd seems to default to the workspace directory, which seems to be the directory containing the vs code project file, and if this is not where your script is located, then your relative include paths are broken.
A solution to this is to insure that your script changes its current directory to the directory where the script is located, and also to append your syspath to the directory where the script is located:
scriptdir = os.path.dirname(os.path.realpath(__file__))
print('dir containing script is %s' % (scriptdir))
# append our extra module directory (in this case Autogen) onto the script directory
sys.path.append(os.path.join(scriptdir, 'Autogen'))
# also change cwd to where the script is located (helps for finding relative files)
print('============\ncwd is %s' %(os.getcwd()))
os.chdir(scriptdir)
print('============\ncwd after change to script dir is %s' %(os.getcwd()))
All the above steps will help to make your script run well, but they will not help for intellisense or code completion. To have the code completion run well, you must create a .env
file (usually in the same directory as your .vscode directory) and in your .env file you add the directories where you want vscode to look for extra python modules
Contents of .env file
PYTHONPATH="someDirRelativeTowhereYourVSCodeProjectLives\\Autogen"
This solution helps me to solve this issue permanently.Steps are given below.