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)
2
Answers
Your launch.json is not matched with your structure.
main.py
andexample.py
is not under the src folder in your file structure.Modify launch.json as follows:
Use the green triangle button to debug
main.py
at Run and Debug panel, or useRun --> Start Debugging/Run without Debugging
.You better modify the two configurations in Launch to different names, so that it is easier to distinguish to choose from.
If you’re running the file using the play button at the top right or its dropdown entries, or using the
Python: Run Python File in Terminal
orJupyter: Run Current File in Interactive Window
commands in the command palette, those don’t pick on things you put in your launch.json configs as far as I know. You need to actually run the launch config from the Run and Debug View, select the launch config you want to run, and then click the play button in the Run and Debug View.If you insist on using the
Python: Run Python File in Terminal
command, or actions based on that command, you can look into using theterminal.integrated.env.*
VS Code settings- either in your user or workspace settings.json file. Ex.I’m not sure about workarounds for Jupyter notebooks though.