Use virtualenv with Python with Visual Studio Code - python

I have a Python project and navigation/autocomplete work perfectly within files in the project. I want to specify a virtualenv so that navigation/autocomplete work with packages inside that virtualenv.
I tried this in settings.py, but navigation/autocomplete does not work. Also by setting "python.pythonPath":"~/dev/venvs/proj/bin/python killed the original navigation/autocomplete.
{
"python.autoComplete.extraPaths": [
"~/dev/venvs/proj",
"~/dev/venvs/proj/lib"
]
}

With the latest update to the extension all you need to do is just specify the "python.pythonPath" as follows.
The values for "python.autoComplete.extraPaths" will be determined during runtime, but you are still free to specify custom paths in there.
Please, remember to restart Visual Studio Code once the necessary changes have been made.
{
"python.pythonPath": "~/dev/venvs/proj/bin/python"
}

As of September 2016 (according to the GitHub repository documentation of the extension) you can just execute a command from within Visual Studio Code that will let you select the interpreter from an automatically generated list of known interpreters (including the one in your project's virtual environment).
How can I use this feature?
Select the command Python: Select Workspace Interpreter(*) from the command palette (F1).
Upon selecting the above command a list of discovered interpreters will be displayed in a quick pick list.
Selecting an interpreter from this list will update the settings.json file automatically.
(*) This command has been updated to Python: Select Interpreter in the latest release of Visual Studio Code (thanks #nngeek).
Also, notice that your selected interpreter will be shown at the left side of the statusbar, e.g., Python 3.6 64-bit. This is a button you can click to trigger the Select Interpreter feature.

Quite simple with the latest version of Visual Studio Code, if you have installed the official Python extension for Visual Studio Code:
Shift + Command + P
Type: Python: Select Interpreter
Choose your virtual environment.
Official site

With the latest Python extension for Visual Studio Code, there is a venvPath Setting:
// Path to folder with a list of Virtual Environments (e.g. ~/.pyenv, ~/Envs, ~/.virtualenvs).
"python.venvPath": "",
On Mac OS X, go to Code → Preferences → Settings and scroll down to Python Configuration.
Look for "python.venvPath: "", and click the pencil on the left-hand side to open up your user settings. Finally, add the path to where you store your virtual environments.
If you are using virtuanenvwrapper, or you have put all your virtual environment setting in one folder, this will be the one for you.
After you have configured "python.venvPath", restart Visual Studio Code. Then open the command palette and look for "Python: Select Interpreter". At this point, you should see the interpreter associated with the virtual environment you just added.

Another way is to open Visual Studio Code from a terminal with the virtualenv set and need to perform F1 Python: Select Interpreter and select the required virtualenv.

I put the absolute path of the virtual environment Python executable as well has the packages. I then restarted Visual Studio Code.
I am trying to get ${workspaceRoot} to avoid hardcoding absolute paths.
{
"editor.rulers": [80,100],
"python.pythonPath": "/home/jesvin/dev/ala/venv/bin/python",
"python.autoComplete.extraPaths": [
"/home/jesvin/dev/ala/venv/lib/python2.7",
"/home/jesvin/dev/ala/venv/lib/python2.7/site-packages"
]
}

I was able to use the workspace setting that other people on this page have been asking for.
In Preferences, ⌘+P, search for python.pythonPath in the search bar.
You should see something like:
// Path to Python, you can use a custom version of Python by modifying this setting to include the full path.
"python.pythonPath": "python"
Then click on the WORKSPACE SETTINGS tab on the right side of the window. This will make it so the setting is only applicable to the workspace you're in.
Afterwards, click on the pencil icon next to "python.pythonPath". This should copy the setting over the workspace settings.
Change the value to something like:
"python.pythonPath": "${workspaceFolder}/venv"

a) Modify Visual Studio Code default virtual env path setting. It's called "python.venvPath". You do this by going into code->settings and scroll down for python settings.
b) Restart VS Code
c) Now if you do Shift + Command + P and type Python: Select Interpreter
you should see list of your virtual environments.

It seems to be (as of 2018.03) in code-insider. A directive has been introduced called python.venvFolders:
"python.venvFolders": [
"envs",
".pyenv",
".direnv"
],
All you need is to add your virtualenv folder name.

On Mac OS X using Visual Studio Code version 1.34.0 (1.34.0) I had to do the following to get Visual Studio Code to recognise the virtual environments:
Location of my virtual environment (named ml_venv):
/Users/auser/.pyvenv/ml_venv
auser#HOST:~/.pyvenv$ tree -d -L 2
.
└── ml_venv
├── bin
├── include
└── lib
I added the following entry in Settings.json: "python.venvPath": "/Users/auser/.pyvenv"
I restarted the IDE, and now I could see the interpreter from my virtual environment:

I got this from YouTube Setting up Python Visual Studio Code... Venv
OK, the video really didn't help me all that much, but... the first comment under (by the person who posted the video) makes a lot of sense and is pure gold.
Basically, open up Visual Studio Code' built-in Terminal. Then source <your path>/activate.sh, the usual way you choose a venv from the command line. I have a predefined Bash function to find & launch the right script file and that worked just fine.
Quoting that YouTube comment directly (all credit to aneuris ap):
(you really only need steps 5-7)
1. Open your command line/terminal and type `pip virtualenv`.
2. Create a folder in which the virtualenv will be placed in.
3. 'cd' to the script folder in the virtualenv and run activate.bat (CMD).
4. Deactivate to turn of the virtualenv (CMD).
5. Open the project in Visual Studio Code and use its built-in terminal to 'cd' to the script folder in you virtualenv.
6. Type source activates (in Visual Studio Code I use the Git terminal).
7. Deactivate to turn off the virtualenv.
As you may notice, he's talking about activate.bat. So, if it works for me on a Mac, and it works on Windows too, chances are it's pretty robust and portable. 😀

Related

(False) import error warning with global PyLint in virtual environment in Visual Studio Code

I use Visual Studio Code for coding in Python.
In my python file, I stated the following imports:
import requests
from bs4 import BeautifulSoup
I created a virtual environment, installed all necessary packages with pip install inside the virtual environment and the python script runs fine.
In Visual Studio Code, I modified the settings to use PyLint which is installed on the global level (meaning the default python interpreter) so I don't need to install pylint in my virtual environment in order to avoid for it appearing in my requirements.txt. My .vscode/settings.json looks like this:
{
"python.pythonPath": "/Users/pazifik/.virtualenvs/fun-image-scraper/bin/python",
"python.linting.enabled": true,
"python.linting.pylintEnabled": true,
"python.linting.pylintPath": "/opt/homebrew/bin/pylint"
}
Visual Studio Code seems to pick up Pylint correctly, however in the "Problems" view it shows this:
Unable to import 'requests' pylint(importError) [3, 1]
Unable to import 'bs4' pylint(importError) [4, 1]
The reason is probably that the global installed PyLint cannot see the packages inside the virtual environment. The chosen Python interpreter in Visual Studio Code is the Python interpreter from the virtual environment.
How can I get rid of these (false) import errors in Visual Studio Code?
EDIT:
To better visualize my problem and settings, here some screenshots:
pip list of installed packages in virtual environment
pip show of requestspackage in virtual environment
"Problems" view (however! the script runs fine as mentioned, just the errors displayed there are confusing hence my question)
PyLint installed in global environment with default interpreter
Very sorry for my previous answer, I had modified the pylintArgs before, so I have not found out the problem.
You can add this in the settings.json:
"python.envFile": "${workspaceFolder}/.env",
And create a file named .env under the workspace folder, and add this in it:
PYTHONPATH=/Users/pazifik/.virtualenvs/fun-image-scraper/lib/python3.9/site-packages
Explain:
Although you have selected the virtual environment in the VSCode, and you can find the PYTHONPATH has been modified in the terminal, but the pylint did not route through the terminal, so it will not get the modified PYTHONPATH.
When the terminal settings are used, PYTHONPATH affects any tools that
are run within the terminal by a user, as well as any action the
extension performs for a user that is routed through the terminal such
as debugging. However, in this case when the extension is performing
an action that isn't routed through the terminal, such as the use of a
linter or formatter, then this setting will not have an effect on
module look-up.
When PYTHONPATH is set using an .env file, it will affect anything the
extension does on your behalf and actions performed by the debugger,
but it will not affect tools run in the terminal.
You can refer to the official docs.
Sorry, but it works well on my computer. Could you reconfirm which python interpreter you have selected, and where the python packages you have installed?
You can get which python interpreter you have used from the bottom-left of the VSCode or the environment name in the terminal:
The setting of python.pythonPath in the settings.json can not determine which python interpreter you are using.
And maybe you just installed the packages in the different environments, could you take the command of pip show {packagename} to check where the packages have been installed?

Why Virtual Studio Code can't find my virtual environments instaled modules?

Always when I create a new Python project file, in Visual Studio Code, and I import some modules, it marks the ones VSC can't find, but they are already installed in virtual environments.
How can I fix this bug? Thanks!
Select and activate an environment
By default, the Python extension looks for and uses the first Python interpreter it finds in the system path. If it doesn't find an interpreter, it issues a warning. On macOS, the extension also issues a warning if you're using the OS-installed Python interpreter, because you typically want to use an interpreter you install directly. In either case, you can disable these warnings by setting python.disableInstallationCheck to true in your user settings.
Check this link: https://code.visualstudio.com/docs/python/environments

How can I create a workspace in Visual Studio Code?

I have this very beginner question that I happened to install Visual Studio Code on my Mac, and every time I tried to run a simple Python program on that, it said that I need a workspace to run, so how do I create the workspace?
I am not sure how you try to run this program, but you can just go to menu View → Terminal and type python your_program.py in TERMINAL from the folder where your program is located.
And please check if you have not accidentally installed Visual Studio instead of Visual Studio Code (those are two completely different programs).
VSCode workspaces are basically just folders. If you open an empty folder in VSCode it will get treated as a workspace, and you can add any scripts you want to it. VSCode will create a new hidden folder in the folder you chose that will hold settings for the workspace. For python, make sure you install the python extension (just grab the one with the most downloads) and follow the instructions there to make sure your python environment is properly configured. If you're using git, you might want to add that hidden folder to the gitignore.

Visual Studio Code pylint: Unable to import 'protorpc'

I'm using pylint in Visual Studio Code to develop a Google App Engine (GAE) Cloud Endpoint API in Python. I'm unable to resolve a lint error. I don't know what's causing the error, but at a guess, pylint cannot find the protorpc library?
The recommended fix in Troubleshooting Linting is to configure workspace settings to point to fully qualified python executable. I have done this, but the lint error remains.
protorpc itself is installed to:
~/google-cloud-sdk/platform/google_appengine/lib/protorpc-1.0/protorpc
...and this contains the remote.py module that cannot be imported:
__init__.py generate_python.py protojson.py transport.py
definition.py google_imports.py protourlencode.py util.py
descriptor.py message_types.py registry.py webapp
generate.py messages.py remote.py wsgi
generate_proto.py protobuf.py static
I've added this path to $PYTHONPATH (along with the kitchen sink):
export GOOGLE_CLOUD_SDK=~/google-cloud-sdk
export APPENGINE_PATH=$GOOGLE_CLOUD_SDK/platform/google_appengine
export PYTHONPATH=$PYTHONPATH:$GOOGLE_CLOUD_SDK
export PYTHONPATH=$PYTHONPATH:$GOOGLE_CLOUD_SDK/lib
export PYTHONPATH=$PYTHONPATH:$GOOGLE_CLOUD_SDK/lib/googlecloudsdk
export PYTHONPATH=$PYTHONPATH:$GOOGLE_CLOUD_SDK/lib/googlecloudsdk/api_lib
export PYTHONPATH=$PYTHONPATH:$GOOGLE_CLOUD_SDK/platform/google_appengine/lib
export PYTHONPATH=$PYTHONPATH:$GOOGLE_CLOUD_SDK/platform/google_appengine/lib/protorpc-1.0/protorpc
The application runs locally and also when deployed, so this appears to be just a lint error, but it's frustrating that I can't solve it.
Using third-party libraries states:
The Python runtime in the standard environment includes the Python
standard library, the App Engine libraries, and a few bundled
third-party packages.
Because of this, I assumed 'the App Engine libraries' includes protorpc, but I'm unsure. Moreover, Adding the Cloud Endpoints Frameworks library to the sample API only requires google-endpoints be installed to the app's lib directory:
pip install -t lib google-endpoints --extra-index-url=https://gapi-pypi.appspot.com/admin/nurpc-dev --ignore-installed
My point is, I don't think I've not installed something, and I don't think I'm missing anything in my (web) app's lib directory.
Changing the library path worked for me. Hitting Ctrl + Shift + P and typing python interpreter and choosing one of the available shown. One was familiar (as pointed to a virtualenv that was working fine earlier) and it worked. Take note of the version of python you are working with, either 2.7 or 3.x and choose accordingly
I was facing same issue (VS Code).Resolved by below method
1) Select Interpreter command from the Command Palette (Ctrl+Shift+P)
2) Search for "Select Interpreter"
3) Select the installed python directory
Ref:- https://code.visualstudio.com/docs/python/environments#_select-an-environment
Open the settings file of your Visual Studio Code (settings.json) and add the library path to the "python.autoComplete.extraPaths" list.
"python.autoComplete.extraPaths": [
"~/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2",
"~/google-cloud-sdk/platform/google_appengine",
"~/google-cloud-sdk/lib",
"~/google-cloud-sdk/platform/google_appengine/lib/endpoints-1.0",
"~/google-cloud-sdk/platform/google_appengine/lib/protorpc-1.0"
],
For your case, add the following code to vscode's settings.json.
"python.linting.pylintArgs": [
"--init-hook='import sys; sys.path.append(\"~/google-cloud-sdk/platform/google_appengine/lib\")'"
]
For the other who got troubles with pip packages, you can go with
"python.linting.pylintArgs": [
"--init-hook='import sys; sys.path.append(\"/usr/local/lib/python3.7/dist-packages\")'"
]
You should replace python3.7 above with your python version.
Spent hours trying to fix the error for importing local modules. Code execution was fine but pylint showed:
Unable to import '<module>'
Finally figured:
First of all, select the correct python path. (In the case of a virtual environment, it will be venv/bin/python). You can do this by hitting
Make sure that your pylint path is the same as the python path you chose in step 1. (You can open VS Code from within the activated venv from terminal so it automatically performs these two steps)
The most important step: Add an empty __init__.py file in the folder that contains your module file. Although python3 does not require this file for importing modules, I think pylint still requires it for linting.
Restart VS Code, the errors should be gone!
I've not played around with all possibilities, but at least I had the impression that this could be a python version related issue. No idea why, I just trusted my gut.
Thus I just changed the pythonPath to python3 (default: python):
"python.pythonPath": "python3"
I reinstalled the dependencies (including pylint!!!) with
pip3 install <package> --user
... and after restarting vs code, everything looked fine.
HTH Kai
I was still getting these errors even after confirming that the correct python and pylint were being used from my virtual env.
Eventually I figured out that in Visual Studio Code I was A) opening my project directory, which is B) where my Python virtual environment was, but I was C) running my main Python program from two levels deeper. Those three things need to be in sync for everything to work.
Here's what I would recommend:
In Visual Studio Code, open the directory containing your main Python program. (This may or may not be the top level of the project directory.)
Select Terminal menu > New Terminal, and create an virtual environment directly inside the same directory.
python3 -m venv env
Install pylint in the virtual environment. If you select any Python file in the sidebar, Visual Studio Code will offer to do this for you. Alternatively, source env/bin/activate then pip install pylint.
In the blue bottom bar of the editor window, choose the Python interpreter env/bin/python. Alternatively, go to Settings and set "Python: Python Path." This sets python.pythonPath in Settings.json.
The simplest solution is to create a .env file in your project root with this content:
PYTHONPATH=.
You don't need __init__.py files. It works even if your code is in src dir, and unit tests in tests subdirs. This helped pylint and pytest to find all the modules.
For more info, see https://code.visualstudio.com/docs/python/environments#_environment-variable-definitions-file
The visual studio default setting should be the same as the interpreter path.
Change VS code default setting: windows: File > Preferences > Settings
{
"python.pythonPath": "C:\\Users\\Anaconda3\\pythonw.exe",
"workbench.startupEditor": "newUntitledFile"
}
Find the right interpreter:
windows: Ctrl+Shift+P->select interpreter:
the path of that interpreter should be same as the version you are working on.
First I will check the python3 path where it lives
And then in the VS Code settings just add that path, for example:
"python.pythonPath": "/usr/local/bin/python3"
I resolved this by adding the protorpc library to the $PYTHONPATH environment variable. Specifically, I pointed to the library installed in my App Engine directory:
export PYTHONPATH=$PYTHONPATH:/Users/jackwootton/google-cloud-sdk/platform/google_appengine/lib/protorpc-1.0
After adding this to ~/.bash_profile, restarting my machine and Visual Studio Code, the import errors went away.
For completeness, I did not modify any Visual Studio Code settings relating to Python. Full ~/.bash_profile file:
export PATH=/Users/jackwootton/protoc3/bin:$PATH
export PYTHONPATH=/Users/jackwootton/google-cloud-sdk/platform/google_appengine
export PYTHONPATH=$PYTHONPATH:/Users/jackwootton/google-cloud-sdk/platform/google_appengine/lib/protorpc-1.0
# The next line updates PATH for the Google Cloud SDK.
if [ -f '/Users/jackwootton/google-cloud-sdk/path.bash.inc' ]; then source '/Users/jackwootton/google-cloud-sdk/path.bash.inc'; fi
# The next line enables shell command completion for gcloud.
if [ -f '/Users/jackwootton/google-cloud-sdk/completion.bash.inc' ]; then source '/Users/jackwootton/google-cloud-sdk/completion.bash.inc'; fi
I find the solutions stated above very useful. Especially the Python's Virtual Environment explanation by jrc.
In my case, I was using Docker and was editing 'local' files (not direcly inside the docker).
So I installed Remote Development extension by Microsoft.
ext install ms-vscode-remote.vscode-remote-extensionpack
More details can be found at https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack
I should say, it was not easy to play around at first.
What worked for me was...
1. starting docker
2. In vscode, Remote-container: Attach to running container
3. Adding folder /code/<path-to-code-folder> from root of the machine to vscode
and then installing python extension + pylint
Another solution could be generating a pylintrc in project location using command: (this command will by default print the content to terminal and not actually create a file, you need to dump output to .pylintrc)
pylint --generate-rcfile
and then update key init-hook= using:
import sys; sys.path.append("your_project_location")
In my case, I tried flake8, bandit, didn't work, eventually I uninstalled the extension called python (pylance) and everything worked perfectly.
I got the same error on my vscode where I had a library installed and the code working when running from the terminal, but for some reason, the vscode pylint was not able to pick the installed package returning the infamous error:
Unable to import 'someLibrary.someModule' pylint(import-error)
The problem might arise due to the multiple Python installations. Basically you have installed a library/package on one, and vscode pylint is installed and running from another installation. For example, on macOS and many Linux distros, there are by default Python2 installed and when you install Python3 this might cause confusion. Also on windows the Chocolatey package manager might cause some mess and you end up with multiple Python installations. To figure it out if you are on a *nix machine (i.e., macOS, GNU/Linux, BSD...), use the which command, and if you are on Windows, use the where command to find the installed Python interpreters. For example, on *nix machines:
which python3
and on Windows
where python
then you may want to uninstall the ones you don't want. and the one you want to use check if the package causing above issue is installed by
python -c "import someLibrary"
if you get an error then you should install it by for example pip:
pip install someLibrary
then on vscode press ⌘⇧P if you are on a mac and CtrlShiftP on other operating systems. Then type-select the >python: Select Interpreter option and select the one you know have the library installed. At this moment vscode might asks you to install pyling again, which you just go on with.
I resolve this error by below step :
1 : first of all write this code in terminal :
...$ which python3
/usr/bin/python3
2 : Then :
"python.pythonPath": "/users/bin/python",
done.
I had same problem for pyodbc , I had two version of python on my Ubuntu (python3.8 and python3.9), problem was: package installed on python3.8 location but my interpreter was for python3.9. i installed python3.8 interpreter in command palette and it fixed.
Other solutions not working for me (multiple workspaces)
Create ~/.vscode/workspace.env with following content
PYTHONPATH=$PYTHONPATH:/Users/jackwootton/protoc3/bin
Go to Workspace Settings: ⌘ / Ctrl⇧P → Workspace Settings.
Add next config line there:
"python.envFile": "/Users/jackwootton/.vscode/workspace.env",
Reload Window.
This solution better than #Jack, because it doesn't modify a global variable for all system, just for your project workspace.
In my case, the packages got installed in the global Python installation path and not in the venv, even though I had the virtual environment activated at the time of installation.
I could see this when I switched to the base environment (by a click on the bottom left status field of the chosen interpreter) and saw that the package could be imported.
I could only solve this by removing the venv and installing it again.
pylint is run in the vscode terminal, and its output transferred to the editor. Therefore the terminal environment settings need to match those in the command line outside vscode. Specifically, in settings.json:
"terminal.integrated.env.linux": {
"PYTHONPATH": "/path/to/library/files/you/want/pylint/to/FINALLY/EXPLETIVE/FIND"
},

Activating Anaconda Environment in VsCode

I have Anaconda working on my system and VsCode working, but how do I get VsCode to activate a specific environment when running my python script?
Simply use
shift + cmd + P
Search Select Interpreter
Select it and it will show you the list of your virtual environment created via conda and other python versions
select the environment and you are ready to go.
Quoting the 'Select and activate an environment' docs
Selecting an interpreter from the list adds an entry for python.pythonPath with
the path to the interpreter inside your Workspace Settings.
If Anaconda is your default Python install then it just works if you install the Microsoft Python extension.
The following should work regardless of Python editor or if you need to point to a specific install:
In settings.json edit python.path with something like
"python.pythonPath": "C:\\Anaconda3\\envs\\py34\\python.exe"
Instructions to edit settings.json
Setting python.pythonPath in VSCode's settings.json file doesn't work for me, but another method does. According to the Anaconda documentation at Microsoft Visual Studio Code (VS Code):
When you launch VS Code from Navigator, VS Code is configured to use the Python interpreter in the currently selected environment.
The best option I found is to set the python.venvPath parameter in vscode settings to your anaconda envs folder.
"python.venvPath": "/Users/[...]/Anaconda3/envs"
Then if you bring up the command palette (ctl + shift + P on windows/linux, cmd + shift + P on mac) and type Python: Select Workspace Interpreter all your envs will show up and you can select which env to use.
The python extension will also need to be installed for the Select Workspace Interpreter option.
Note: The Select Workspace Interpreter takes around 10 seconds to come up on my computer using the current version of VSCode.
Although approved answer is correct, I want to show a bit different approach (based on this answer).
Vscode can automatically choose correct anaconda environment if you start vscode from it. Just add to user/workspace settings:
{
"python.pythonPath": "C:/<proper anaconda path>/Anaconda3/envs/${env:CONDA_DEFAULT_ENV}/python"
}
It works on Windows, macOS and probably Unix. Further read on variable substitution in vscode: here.
Unfortunately, this does not work on macOS. Despite the fact that I have export CONDA_DEFAULT_ENV='$HOME/anaconda3/envs/dev' in my .zshrc and "python.pythonPath": "${env.CONDA_DEFAULT_ENV}/bin/python",
in my VSCode prefs, the built-in terminal does not use that environment's Python, even if I have started VSCode from the command line where that variable is set.
Just launch the VS Code from the Anaconda Navigator. It works for me.
Find a note here: https://code.visualstudio.com/docs/python/environments#_conda-environments
As noted earlier, the Python extension automatically detects existing
conda environments provided that the environment contains a Python
interpreter. For example, the following command creates a conda
environment with the Python 3.4 interpreter and several libraries,
which VS Code then shows in the list of available interpreters:
conda create -n env-01 python=3.4 scipy=0.15.0 astroid babel
In contrast, if you fail to specify an interpreter, as with conda create
--name env-00, the environment won't appear in the list.
If you need an independent environment for your project:
Install your environment to your project folder using the --prefix option:
conda create --prefix C:\your\workspace\root\awesomeEnv\ python=3
In VSCode launch.json configuration set your "pythonPath" to:
"pythonPath":"${workspaceRoot}/awesomeEnv/python.exe"
Python Path is now deprecated and now you should set Conda Path instead. This way you can pick different environements on the fly.
Click ctrl + , then search for Conda Path and add absolute path to script, e.g.:
C:\Users\{myUser}\miniconda3\Scripts\conda.exe
Pick specific environment for each project in bottom left corner or through Command Pallete (ctrl + Shift + P -> search Python: Select Interpreter)
The simplest way to do it -
First open up terminal or command line and navigate to the project directory where you created the virtual environment.
Then activate the virtual environment with the command
conda activate venv_name
Once activated, in terminal type -
code .
This will open the vscode with the activated virtual environment. Look at the bottom of the pic. The dot after code . tells terminal to open the current directory in vscode.
I found out that if we do not specify which python version we want the environment which is created is completely empty. Thus, to resolve this issue what I did is that I gave the python version as well. i.e
conda create --name env_name python=3.6
so what it does now is that it installs python 3.6 and now we can select the interpreter. For that follow the below-mentioned steps:
Firstly, open the command palette using Ctrl + Shift + P
Secondly, Select Python: select Interpreter
Now, Select Enter interpreter path
We have to add the path where the env is, the default location will be
C:\Users\YourUserName\Anaconda3\envs\env_name
Finally, you have successfully activated your environment.
It might now be the best way but it worked for me. Let me know if there is any issue.
I found a hacky solution replace your environment variable for the original python file so instead it can just call from the python.exe from your anaconda folder, so when you reference python it will reference anaconda's python.
So your only python path in env var should be like:
"C:\Anaconda3\envs\py34\", or wherever the python executable lives
If you need more details I don't mind explaining. :)
As I was not able to solve my problem by suggested ways, I will share how I fixed it.
First of all, even if I was able to activate an environment, the corresponding environment folder was not present in C:\ProgramData\Anaconda3\envs directory.
So I created a new anaconda environment using Anaconda prompt,
a new folder named same as your given environment name will be created in the envs folder.
Next, I activated that environment in Anaconda prompt.
Installed python with conda install python command.
Then on anaconda navigator, selected the newly created environment in the 'Applications on' menu.
Launched vscode through Anaconda navigator.
Now as suggested by other answers, in vscode, opened command palette with Ctrl + Shift + P keyboard shortcut.
Searched and selected Python: Select Interpreter
If the interpreter with newly created environment isn't listed out there, select Enter Interpreter Path and choose the newly created python.exe which is located similar to C:\ProgramData\Anaconda3\envs\<your-new-env>\ .
So the total path will look like C:\ProgramData\Anaconda3\envs\<your-nev-env>\python.exe
Next time onwards the interpreter will be automatically listed among other interpreters.
Now you might see your selected conda environment at bottom left side in vscode.
"python.pythonPath" is deprecated, quote from vscode:
The "python.pythonPath" setting in your settings.json is no longer
used by the Python extension. If you want, you can use a new setting
called "python.defaultInterpreterPath" instead. Keep in mind that you
need to change the value of this setting manually as the Python
extension doesn’t modify it when you change interpreters. Learn more.
Thus, IF you want to assign the path manually (not reccommended, as explained above), open the "settings.json" of your workspace or the default one and use
{
"python.defaultInterpreterPath": "C:\\Users\\MYUSER\\anaconda3\\envs\\testenv\\python.exe"
}

Categories