[python] How to setup virtual environment for Python in VS Code?

In my project folder I created venv folder.

python -m venv venv

When I in VS Code run command select python interpreter my venv folder is not shown. I went one level up like suggested here but VS Code doesn't see my virtual interpreter.

What did I miss?

This question is related to python visual-studio-code virtualenv

The answer is


P.S:

  • I have been using vs code for a while now and found an another way to show virtual environments in vs code.

  • Go to the parent folder in which venv is there through command prompt.

  • Type code . and Enter. [Working on both windows and linux for me.]

  • That should also show the virtual environments present in that folder.

Original Answer

I almost run into same problem everytime I am working on VS-Code using venv. I follow below steps, hope it helps:

  1. Go to File > preferences > Settings.

  2. Click on Workspace settings.

  3. Under Files:Association, in the JSON: Schemas section, you will find Edit in settings.json , click on that.

  4. Update "python.pythonPath": "Your_venv_path/bin/python" under workspace settings. (For Windows): Update "python.pythonPath": "Your_venv_path/Scripts/python.exe" under workspace settings.

  5. Restart VSCode incase if it still doesn't show your venv.


With a newer VS Code version it's quite simple.

Open VS Code in your project's folder.

Then open Python Terminal (Ctrl-Shift-P: Python: Create Terminal)

In the terminal:

python -m venv .venv

you'll then see the following dialog: enter image description here

click Yes

Then Python: Select Interpreter (via Ctrl-Shift-P)

and select the option (in my case towards the bottom)

Python 3.7 (venv) ./venv/Scripts/python.exe

If you see

Activate.ps1 is not digitally signed. You cannot run this script on the current system.

you'll need to do the following: https://stackoverflow.com/a/18713789/2705777

For more information see: https://code.visualstudio.com/docs/python/environments#_global-virtual-and-conda-environments


I was having the same issue until I worked out that I was trying to make my project directory and the virtual environment one and the same - which isn't correct.

I have a \Code\Python directory where I store all my Python projects. My Python 3 installation is on my Path.

If I want to create a new Python project (Project1) with its own virtual environment, then I do this:

python -m venv Code\Python\Project1\venv

Then, simply opening the folder (Project1) in Visual Studio Code ensures that the correct virtual environment is used.


I fixed the issue without changing the python path as that did not seem like the right solution for me. The following solution worked for me, hopefully it works for you as well :))

  1. Open cmd in windows / shell in Linux/Mac.
  2. Activate your virtualenv (using source activate / activate.bat / activate.ps1 if using power shell)

    C:\Users\<myUserName>\Videos\myFolder>django-project\Scripts\activate.bat (django-project) C:\Users\<myUserName>\Videos\myFolder>

  3. Navigate to your project directory and open vscode there.

    (django-project) C:\Users\prash\Videos\myFolder\projects>code .

  4. in VS Code, goto File --> Preferences --> Settings (dont worry you dont need to open the json file)

  5. In the setting search bar search for virtual / venv and hit enter. You should find the below in the search bar:

Python: Venv Folders Folders in your home directory to look into for virtual environments (supports pyenv, direnv and virtualenvwrapper by default).

  1. Add item, and then enter the path of the scripts of your virtuanenv which has the activate file in it. For example in my system, it is:

    C:\Users\<myUserName>\Videos\myFolder\django-project\Scripts\

  2. Save it and restart VS Code.

  3. To restart, open cmd again, navigate to your project path and open vs code. (Note that your venv should be activated in cmd before you open vs code from cmd)

Command to open vs code from cmd:

code .

How to setup virtualenv in VS code


There is a VSCode extension called "Python Auto Venv" that automatically detects and uses your virtual environment if there is one.


Many have mentioned the python.pythonPath method.

Another way is adding a envFile in the launch.json like this:

    {
        "name": "Run",
        "etc": "etc",
        "envFile": "${workspaceFolder}/venv"
    }

This is an adding to @Sam answer that though is correct is missing the fact that anytime you open a folder in visual studio code, it create a .vscode folder, but those can be multiple, created any time you eventually open a directory. The .vscode folder has JSON objects that content properties such "setting.json", in which one declare the Interpreter to use at that ".vscode" level( refer to this for more clarifications What is a 'workspace' in VS Code?).

{
   {
     "python.pythonPath": "VirtualEnPath/bin/python3.6"
   }
}

So potentially you could open VS code at another level in the virtual Env, it create another .vscode folder that assume as Python directory those of the global machine and so having such error, and has I experienced has nothing to do if the Virtual Env is activated or not.

This indeed what happened to me, I have indeed a DjangoRESTAPI_GEN folder in which I initially opened the IDE and it did recognize the Virtual Env Python path, the a few days after I opened it at the level where git is, so it did created another .vscode, that picked the global Python Interpreter, causing my lint in the Virtual Environment not been used, and the virtual env interpreter not even showed in "select python interpreter". But as wrote opening the IDE at the level where the .vscode that has the settings.json with correct path, it does.

Once you set the correct path in the setting.json and select the virtual env interpreter, then VS Code will automatically activate the VE in its terminal

enter image description here


The question is how to create a new virtual environment in VSCode, that is why telling the following Anaconda solution might not the needed answer to the question. It is just relevant for Anaconda users.

Just create a venv using conda, see here. Afterwards open VSCode and left-click on the VSCode interpreter shown in VSCode at the bottom left:

vscode interpreter info

Choose a virtual environment that pops up in a dropdown of the settings window, and you are done. Mind the answer of @RamiMa.


I had the same problem and the solution was pretty easy:

"If you create a new conda environment while VS Code is running, use the Reload Window command to refresh the environment list shown with Python: Select Interpreter; otherwise you may not see the environment there. It might take a short time to appear; if you don't see it at first, wait 15 seconds then try using the command again."

That's written on Vscode site

Note: to Reload Window: ctrl+shift+p in Vscode, then write reload window


I had the same problem and it was because PowerShell was not updated. Sometimes Windows preserve version 2.* and I had to manually download and install version 3. After that problem solved and I could use virtual environments very well.


Have you activated your environment? Also you could try this: vscode select venv


In vscode select folder and create WS and it will work fine


For Mac users, note this bug: when you click "Enter interpreter path", you have two options: (1) manually enter the path; (2) select the venv file from Finder.

It only works if I manually enter the path. Selecting with Finder yields some strange path like Library/Developer/CommandTools/... which I understand.


  1. If your using vs code on mac, it's important to have your venv installed in the same directory as your workspace.

  2. In my case my venv was in a different directory( not in my project workspace) so a simple cut/copy-paste of my venv to the project workspace did the trick.

  3. As soon as your venv is copied to the project workspace, your vs code will pick that up and show a notification giving you an option to select venv as an interpreter.


Questions with python tag:

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Upgrade to python 3.8 using conda Unable to allocate array with shape and data type How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip How to prevent Google Colab from disconnecting? "UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function? "E: Unable to locate package python-pip" on Ubuntu 18.04 Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session' Jupyter Notebook not saving: '_xsrf' argument missing from post How to Install pip for python 3.7 on Ubuntu 18? Python: 'ModuleNotFoundError' when trying to import module from imported package OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this? Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website How to setup virtual environment for Python in VS Code? Pylint "unresolved import" error in Visual Studio Code Pandas Merging 101 Numpy, multiply array with scalar What is the meaning of "Failed building wheel for X" in pip install? Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed Could not install packages due to an EnvironmentError: [Errno 13] OpenCV !_src.empty() in function 'cvtColor' error ConvergenceWarning: Liblinear failed to converge, increase the number of iterations How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How do I install opencv using pip? How do I install Python packages in Google's Colab? How do I use TensorFlow GPU? How to upgrade Python version to 3.7? How to resolve TypeError: can only concatenate str (not "int") to str How can I install a previous version of Python 3 in macOS using homebrew? Flask at first run: Do not use the development server in a production environment TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array What is the difference between Jupyter Notebook and JupyterLab? Pytesseract : "TesseractNotFound Error: tesseract is not installed or it's not in your path", how do I fix this? Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'" How do I resolve a TesseractNotFoundError? Trying to merge 2 dataframes but get ValueError Authentication plugin 'caching_sha2_password' is not supported Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

Questions with visual-studio-code tag:

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error Cannot edit in read-only editor VS Code How to setup virtual environment for Python in VS Code? Pylint "unresolved import" error in Visual Studio Code Why do I keep getting Delete 'cr' [prettier/prettier]? How to set up devices for VS Code for a Flutter emulator VSCode single to double quote automatic replace js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check How can I clear the terminal in Visual Studio Code? Is there any way to set environment variables in Visual Studio Code? How to connect TFS in Visual Studio code How to shift a block of code left/right by one space in VSCode? How to add a new project to Github using VS Code Is there a way to remove unused imports and declarations from Angular 2+? How to create a Java / Maven project that works in Visual Studio Code? Select all occurrences of selected word in VSCode How to see local history changes in Visual Studio Code? VSCode cannot find module '@angular/core' or any other modules #include errors detected in vscode ESLint not working in VS Code? Visual Studio Code - Target of URI doesn't exist 'package:flutter/material.dart' What is a 'workspace' in Visual Studio Code? VSCode Change Default Terminal Visual Studio Code Search and Replace with Regular Expressions Visual Studio Code open tab in new window Activating Anaconda Environment in VsCode Error message "Linter pylint is not installed" Switch focus between editor and integrated terminal in Visual Studio Code Collapse all methods in Visual Studio Code How do I use Bash on Windows from the Visual Studio Code integrated terminal? Changing the git user inside Visual Studio Code Color theme for VS Code integrated terminal How to compare different branches in Visual Studio Code How to restart VScode after editing extension's config? Moving Panel in Visual Studio Code to right side Restore a deleted file in the Visual Studio Code Recycle Bin VSCode: How to Split Editor Vertically Install a Nuget package in Visual Studio Code How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F How to change the integrated terminal in visual studio code or VSCode PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting How to do tag wrapping in VS code? Debug/run standard java in Visual Studio Code IDE and OS X? Visual Studio Code: How to show line endings How do you format code on save in VS Code Is there a quick change tabs function in Visual Studio Code? Duplicate line in Visual Studio Code Open files always in a new tab In Visual Studio Code How do I merge between two local branches?

Questions with virtualenv tag:

How to setup virtual environment for Python in VS Code? Conda version pip install -r requirements.txt --target ./lib What is the purpose of "pip install --user ..."? What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc? ImportError: No module named 'encodings' how to specify new environment location for conda create Use virtualenv with Python with Visual Studio Code in Ubuntu Is it ok having both Anacondas 2.7 and 3.5 installed in the same time? How to uninstall a package installed with pip install --user Unable to install boto3 Virtualenv Command Not Found How to run Spyder in virtual environment? Where does pip install its packages? Using (Ana)conda within PyCharm Using Python 3 in virtualenv Broken references in Virtualenvs How do I activate a virtualenv inside PyCharm's terminal? How to install a package inside virtualenv? error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied pip installing in global site-packages instead of virtualenv How to activate an Anaconda environment Python: No acceptable C compiler found in $PATH when installing python ImportError: No module named Crypto.Cipher How to avoid "Permission denied" when using pip with virtualenv How can I make a list of installed packages in a certain virtualenv? How do I update pip itself from inside my virtual environment? How to activate virtualenv? How to install a specific version of a package with pip? bash: mkvirtualenv: command not found How to source virtualenv activate in a Bash script Where is virtualenvwrapper.sh after pip install? Make virtualenv inherit specific packages from your global site-packages How do I tell a Python script to use a particular version Upgrade python in a virtualenv Pip install Matplotlib error with virtualenv setting an environment variable in virtualenv Issue with virtualenv - cannot activate No module named pkg_resources How can I install packages using pip according to the requirements.txt file from a local directory? List all virtualenv Activate a virtualenv with a Python script Is it bad to have my virtualenv directory inside my git repository? no module named zlib Comprehensive beginner's virtualenv tutorial? What is the official "preferred" way to install pip and virtualenv systemwide? Is it possible to install another version of Python to Virtualenv? How to install psycopg2 with "pip" on Python? How do you set your pythonpath in an already-created virtualenv? How can I upgrade specific packages using pip and a requirements file? Python virtualenv questions