I would like to import methods from a directory one level above my current working directory. One way to do this is to manually append the directory to sys.path
. I found a better solution for VSCode on this post. The solution described there involves creating a launch.json
file with a configuration line that looks like "env": {"PYTHONPATH": "/tmp/a:/tmp/b"}
. This method is documented here. Note that defining the environment variable in .env
file works, but I would like to use the VSCode variable $workspaceFolder
, which is not possible in .env
.
Using launch.json
, I am not able to access the modified PYTHONPATH
. In both interactive mode and Run mode, the path doesn't reflect the desired changes.
Following is my directory structure:
project/
- .vscode
- launch.json
- conf/
- file1.py
- src/
- file2.py
- main.py
- example.py
The file launch.json
looks like this:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: main",
"type": "python",
"request": "launch",
"module": "main",
"justMyCode": true,
"env": {"PYTHONPATH": "${workspaceFolder}/conf/"}
},
{
"name": "Python: example",
"type": "python",
"request": "launch",
"module": "example",
"justMyCode": true,
"env": {"PYTHONPATH": "${workspaceFolder}/conf/"}
},
]
}
When I run main.py
or example.py
, I don't see the conf
directory in sys.path
. What's the correct way to do this?
Example to print sys.path
:
import sys
print(sys.path)
After diving deeper into docs and other SO posts, and with hints from @JaileDu's and @user's answers, I've found the complete solution to the problem in the OP.
For interactive mode, need to add the following to settings.json
(change .osx
to respective OS in your case:
"terminal.integrated.env.osx": {"PYTHONPATH": "${workspaceFolder}"},
"jupyter.notebookFileRoot": "${workspaceFolder}"
For Run mode, set PYTHONPATH in .env
file (documented here) or launch.json
(see the same documentation page and this blogpost).
Some related SO posts: