I am experimenting with Visual Studio Code and so far, it seems great (light, fast, etc).
I am trying to get one of my Python apps running that uses a virtual environment, but also uses libraries that are not in the site-package of my virtual environment.
I know that in settings.json, I can specify a python.pythonPath setting, which I have done and is pointing to a virtual environment.
I also know that I can add additional paths to python.autoComplete.extraPaths, where thus far I am adding the external libraries. The problem is, when I am debugging, it's failing because it's not finding the libraries specified in python.autoComplete.extraPaths.
Is there another setting that must be used for this?
Thanks
This worked for me:-
in your launch.json profile entry, specify a new entry called "env", and set PYTHONPATH yourself.
"configurations": [
{
"name": "Python",
"type": "python",
"stopOnEntry": false,
"request": "launch",
"pythonPath": "${config.python.pythonPath}",
"program": "${file}",
"cwd": "${workspaceRoot}",
"debugOptions": [
"WaitOnAbnormalExit",
"WaitOnNormalExit",
"RedirectOutput"
],
"env": {
"PYTHONPATH": "/path/a:path/b"
}
}
]
The Python Extension in VS Code has a setting for python.envFile which specifies the path to a file containing environment variable definitions (Refer to: https://code.visualstudio.com/docs/python/environments#_environment-variable-definitions-file). By default it is set to:
"python.envFile": "${workspaceFolder}/.env"
So to add your external libraries to the path, create a file named .env in your workspace folder and add the below line to it if you are using Windows:
PYTHONPATH="C:\path\to\a;C:\path\to\b"
The advantage of specifying the path here is that both the auto-complete as well as debugging work with this one setting itself. You may need to close and re-open VS Code for the settings to take effect.
I had the same issue, malbs answer doesn't work for me until I change semicolon to a colon,you can find it from ZhijiaCHEN's comments
"env": { "PYTHONPATH": "/path/to/a:/path/to/b" }
Alternatively, I have a hack way to achieve the same:
# at the top of project app script:
import sys
sys.path.append('/path/to/a')
sys.path.append('/path/to/b')
You could add a .pth file to your virtualenv's site-packages directory.
This file should have an absotute path per line, for each module or package to be included in the PYTHONPATH.
https://docs.python.org/2.7/install/index.html#modifying-python-s-search-path
Based on https://github.com/microsoft/vscode-python/issues/12085, I added the following to the settings portion of the workspace config file. I'm using Linux. For Windows, use terminal.integrated.env.windows.
"terminal.integrated.env.linux": {
"PYTHONPATH": "addl-path-entry1:addl-path-entry2"
}
I also added an .env file as described by many posts/comments above.
Finally, I added the PyLance extension per https://stackoverflow.com/a/64103291/11262633.
I also reloaded my workspace.
These two changes allowed me to run Python programs using the debugger and the Run menu. AutoComplete is aware of the added path, and my VSCode linter (was the default linter pylint, now ``pylance```) now works.
I made it work through adding "python.analysis.extraPaths" when using Pylance and IntelliCode.
In 2022, the configuration is as file .vscode/settings.json:
{
"python.analysis.extraPaths": ["C:/Program Files/obs-studio/data/obs-scripting/64bit"],
"terminal.integrated.env.windows": {
"PYTHONPATH": "C:/Program Files/obs-studio/data/obs-scripting/64bit;${env:PYTHONPATH}",
"PATH": "C:/Program Files/obs-studio/data/obs-scripting/64bit;${env:PATH}"
}
}
bash escamotage (works with debugger AND autocomplete); need to install code command in PATH (vsc shell command: install...)
#!/bin/bash
#
# vscode python setup
#
function fvscode {
# you just want one of this:
export PYTHONPATH=<your python installation ../bin/python3>
# you may want many of these:
export PYTHONPATH=<your lib dir here>:$PYTHONPATH
# launch vscode
code
}
alias vscode='fvscode'
the launch VSC by typing 'vscode'.
According to the environments doc, the places the extension looks for environments include some defaults and also the setting value for python.venvPath in the workspace settings
eg: "python.venvPath": "~/.virtualenvs"
This allows you to find several (eg: virtualenvs) as mentioned:
To select a specific environment, use the Python: Select Interpreter
command from the Command Palette
Related
I am trying to create a basic Development Container to use with VS Code.
I've been through a few iterations no of versions but keep coming up against the same issue, my VS Code extensions cannot seem to see what packages are installed in my venv.
Files in my workspace:
.devcontainer/devcontainer.json
{
"name": "Existing Dockerfile",
"context": "..",
"dockerFile": "../Dockerfile"
}
venv/ containing pip installed pandas
Dockerfile:
FROM python:3.9
WORKDIR .
COPY my_file.py .
my_file.py
import sys
import pandas
print(sys.path)
Output of sys.path incase relevant is ['/workspaces/yt', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/workspaces/yt/venv/lib/python3.9/site-packages']
The code executes fine when ran but in VS Code the linting tools raise an error that pandas is not accessed.
Any help would be greatly appreciated.
The most likely reason is that the environment in which the pandas library was installed is not the same as the environment you are currently using.
Solution
Use Ctrl+Shift+P to open the command palette and search for Python:Select Interpreter to select a correct interpreter.
If the error is still not resolved, go ahead and try the following methods:
Add configuration in settings.json to point to the pandas library.
// Just an example, please modify it to your own path
"python.analysis.extraPaths": [
// Path to pandas library
"C:\\WorkSpace\\PyTest0802\\.venv\\Lib\\site-packages"
],
The most simple and rude method -- cancel this type of error (use with caution, this method will cause the prompt message that there is such an error to not be displayed)
Add the following configuration to the settings.json file
"python.analysis.diagnosticSeverityOverrides": {
"reportMissingModuleSource": "none",
},
I am trying to debug my python program in VSCode where I'm getting its directory. When I run os.getcwd() from the terminal, I get the correct directory, but when I use the VS Code debug option, it defaults to the "default" path (as set in my registry variable, which is C:\Users<User>\Downloads).
I have created a launch.json file.
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"cwd": "C:\\Users\\<User>\\Documents\\Project\\"
}
]
}
Here I added "cwd", except no matter what value I put here, the value of os.getcwd() returns the default path in debug mode. I have tried putting: the whole path, ${workspaceFolder}, ${fileDirname}, ${fileWorkspaceFolder}.
The launch.json file is in the .vscode folder in my project.
I do not understand why this is happening and would ideally like a fix. None of the other questions on this site on this subject were able to help.
For those that might have the same problem in the future, I found a work-around. (This works without launch.json.)
I manually edited the code from: directory = os.getcwd() to:
dir_path = os.path.dirname(os.path.realpath(__file__))
os.chdir(dir_path)
directory = os.getcwd()
Then the debugger is in the current working directory and is able to see the files I needed it to.
Please use settings similar to the following in "launch.json":
"cwd": "${workspaceFolder}\\a_pythonscript",
When my "main.py" is in the folder "demo_csv" and "lauch.json" uses "cwd": "${workspaceFolder}\\demo",:
Since the python debugging function in VS Code is provided by the Python extension, please try to reinstall the Python extension.
I recently started exploring VS Code for developing Python code and I’m running into an issue when I try to import a module from a subfolder. The exact same code runs perfectly when I execute it in a Jupyter notebook (the subfolders contain the __init__.py files etc.) I believe I followed the instructions for setting up the VS Python extension correctly. Everything else except this one import command works well, but I haven’t been able to figure what exactly is going wrong.
The structure of the project is as follows: The root folder, which is set as the cwd contains two subfolders (src and bld). src contains the py-file that imports a module that is saved in foo.pyin the bld-folder using from bld.foo import foo_function
When running the file, I get the following error: ModuleNotFoundError: No module named ‘bld'. I have several Anaconda Python environments installed and get the same problem with each of them. When copying foo.py to the src directory and using from foo import foo_function everything works.
My launch.json file is as follows:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File (Integrated Terminal)",
"type": "python",
"request": "launch",
"program": "${file}",
"cwd": "${workspaceFolder}",
"env": {"PYTHONPATH": "${workspaceFolder}:${workspaceFolder}/bld"},
"console": "integratedTerminal"
}
]
}
Any ideas or help would be greatly appreciated!
Stefan‘s method worked for me.
Taking as example filesystem:
workspaceFolder/folder/subfolder1/subfolder2/bar.py
I wasn't able to import subfolders like:
from folder.subfolder1.subfolder2 import bar
It said: ModuleNotFoundError: No module named 'folder'
I added to .vscode/settings.json the following:
"terminal.integrated.env.osx": {
"PYTHONPATH": "${workspaceFolder}"
}
I also added at the beginning of my code:
import sys
#[... more imports ...]
sys.path.append(workspaceFolder)
# and then, the subfolder import:
from folder.subfolder1.subfolder2 import bar
Now, it works.
Note: all my folders and subfolders have an empty file named __init__.py. I still had to do the steps described above.
VSCode version: 1.52.0 (from 10-dec-2020)
I think I finally figured out the answer myself: The integrated terminal does not scan the PYTHONPATH from the .env-file. When running the file in an integrated window, the PYTHONPATH is correctly taken from .env, however. So in order to run my script in the terminal I had to add the terminal.integrated.env.* line in my settings.json as follows:
{
"python.pythonPath": "/anaconda3/envs/py36/bin/python",
"python.linting.enabled": true,
"python.linting.pylintEnabled": true,
"python.linting.flake8Enabled": false,
"python.envFile": "${workspaceFolder}/.env",
"terminal.integrated.env.osx": {
"PYTHONPATH": "${workspaceFolder}"
}
}
I'm working on a project which is structured like
Parent Directory
----+ MyPackage
----__init__.py
----file1.py
----+ Tests
----test.py
When I run the tests from terminal, I use
PYTHONATH=./ python ./Tests/test.py
Now, when I try the debug option after installing 'Python Extension', error is raised
Exception has occurred: ModuleNotFoundError
No module names 'MyPackage'
How can I put PYTHONPATH to the debug configuration such that it will taken care?
After some search and trial and error, I found something that works. I'm posting it here so that people looking for the same problem can also try.
I'm not sure whether this is the right way to do t.
Create (or add to) a file .vscode/settings.json the contents as
{
// .. any other settings
"terminal.integrated.env.linux": {
"PYTHONPATH": "${workspaceFolder}"
}
}
Now I'm able to run my project with the package.
In VSCode 1.74.0 I got it to work by putting the path in my debugging launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Python debugging"
"type": "python"
// other settings
"env": {
"PYTHONPATH": "${workspaceFolder}",
}
}
]
}
Using venv I have tried every variation of tinkering with the terminal.integrated.env.x setting, and env/cwd in launch.json and while I could get this scenario OK when running a file, I could not get it working correctly when debugging a file.
So, what I ended up doing was modifying the .venv/bin/activate file locally to add the project to the python path as part of activation. I think this solution is fine as the venv is to be used only with this project and it covers all scenarios of running files within the IDE.
I added this to the bottom of myProject/.venv/bin/activate:
PYTHONPATH="/Users/path/to/your/project/:$PYTHONPATH"
export PYTHONPATH
I started using VS Code for Python development on a Mac and cannot make pylint find a module.
This is my project folder structure:
project_root/
.env
.vscode/
settings.json
lib/
# lib containing necessary modules
sample/
client/
EDAMTest.py
# many more files
I use a virtualenv in which I have installed pylint. The virtual env is activated in the terminal. I started code from within project_root folder via code . in my terminal.
VS Code says it is using the correct interpreter. I can see on the bottom left that it says Python 3.6.1 (virtualenv)
If I want to test the project_root/sample/client/EDAMTest.py code within terminal I can do it via export PYTHONPATH=../../lib; python EDAMTest.py while being in folder project_root/sample/client/.
Now if I am in VS Code, open the file EDAMTest.py, pylint is telling me that it cannot import modules from lib.
Now my question:
How can I add lib to PYTHONPATH in VS Code?
I found several possible ways to do so:
Create a .env file (see [1] below).
Specify PYTHONPATH in .vscode/launch.json file (see [2])
None of the possible solutions I found seem to work.
What am I missing?
[1] Environment variable definitions file
This tells me how to define global (env) vars. So I specified this:
PYTHONPATH="~/.virtualenvs/evernote/bin/python;lib"
But it won't work. Still libs path is not found by pylint
[2] So I did create a launch.json file like so:
{
"name": "Python",
"type": "python",
"request": "launch",
"stopOnEntry": false,
"pythonPath": "${config.python.pythonPath}",
"program": "${file}",
"cwd": "${workspaceRoot}",
"debugOptions": [
"WaitOnAbnormalExit",
"WaitOnNormalExit",
"RedirectOutput"
],
"env": {
"PYTHONPATH": "~/.virtualenvs/evernote/bin/python:lib"
}
}
---
EDIT
Here is a link that tries to address this problem:
Troubleshooting linting
That link tries to address several possible problems, one is this:
... unable to import
The suggested solution is:
Ensure that the pythonPath setting points to a valid Python installation where Pylint is installed.
=> Yes, I did.
Alternately, set the python.linting.pylintPath to an appropriate version of Pylint for the Python interpreter being used.
=> I did, still no success:
My .vscode/settings.json:
{
"python.pythonPath": "~/.virtualenvs/evernote/bin/python",
"python.linting.pylintPath": "~/.virtualenvs/evernote/bin/pylint"
}
It seems that I had to use a colon instead of a semicolon in .env file like so: PYTHONPATH="~/.virtualenvs/evernote/bin/python:lib". That seems to solve the problem.