Python environments in VS Code

An "environment" in Python is the context in which a Python program runs that consists of an interpreter and any number of installed packages.

Note:If you'd like to become more familiar with the Python programming language, reviewMore Python resources.

Types of Python environments

Global environments

By default, any Python interpreter installed runs in its ownglobal environment.For example, if you just runPython,Python 3,orpyat a new terminal (depending on how you installed Python), you're running in that interpreter's global environment. Any packages that you install or uninstall affect the global environment and all programs that you run within it.

Tip:In Python, it is best practice to create a workspace-specific environment, for example, by using a local environment.

Local environments

There are two types of environments that you can create for your workspace:virtualandconda.These environments allow you to install packages without affecting other environments, isolating your workspace's package installations.

Virtual environments

Avirtual environmentis a built-in way to create an environment. A virtual environment creates a folder that contains a copy (or symlink) to a specific interpreter. When you install packages into a virtual environment it will end up in this new folder, and thus isolated from other packages used by other workspaces.

Note:While it's possible to open a virtual environment folder as a workspace, doing so is not recommended and might cause issues with using the Python extension.

Conda environments

Aconda environmentis a Python environment that's managed using thecondapackage manager (seeGetting started with conda).Choosing between conda and virtual environments depends on your packaging needs, team standards, etc.

Python environment tools

The following table lists the various tools involved with Python environments:

Tool Definition and Purpose
pip The Python package manager that installs and updates packages. It's installed with Python 3.9+ by default (unless you are on a Debian-based OS; installPython 3-pipin that case).
venv Allows you to manage separate package installations for different projects and is installed with Python 3 by default (unless you are on a Debian-based OS; installPython 3-venvin that case)
conda Installed withMiniconda.It can be used to manage both packages and virtual environments. Generally used for data science projects.

Creating environments

Using the Create Environment command

To create local environments in VS Code using virtual environments or Anaconda, you can follow these steps: open the Command Palette (⇧⌘P(Windows, LinuxCtrl+Shift+P)), search for thePython: Create Environmentcommand, and select it.

The command presents a list of environment types:VenvorConda.

Create Environment dropdown

If you are creating an environment usingVenv,the command presents a list of interpreters that can be used as a base for the new virtual environment.

Virtual environment interpreter selection

If you are creating an environment usingConda,the command presents a list of Python versions that can be used for your project.

Conda environment Python version selection

After selecting the desired interpreter or Python version, a notification will show the progress of the environment creation and the environment folder will appear in your workspace.

Create environment status notification

Note:The command will also install necessary packages outlined in a requirements/dependencies file, such asrequirements.txt,pyproject.toml,orenvironment.yml,located in the project folder. It will also add a.gitignorefile to the virtual environment to help prevent you from accidentally committing the virtual environment to source control.

Create a virtual environment in the terminal

If you choose to create a virtual environment manually, use the following command (where ".venv" is the name of the environment folder):

# macOS/Linux
# You may need to run `sudo apt-get install Python 3-venv` first on Debian-based OSs
Python 3 -m venv.venv

# Windows
# You can also use `py -3 -m venv.venv`
Python -m venv.venv

Note:To learn more about thevenvmodule, readCreation of virtual environmentson Python.org.

When you create a new virtual environment, a prompt will be displayed in VS Code to allow you to select it for the workspace.

Python environment prompt

Tip:Make sure to update your source control settings to prevent accidentally committing your virtual environment (in for example.gitignore). Since virtual environments are not portable, it typically does not make sense to commit them for others to use.

Create a conda environment in the terminal

The Python extension automatically detects existing conda environments. We recommend you install a Python interpreter into your conda environment, otherwise one will be installed for you after you select the environment. For example, the following command creates a conda environment namedenv-01with a Python 3.9 interpreter and several libraries:

conda create -n env-01 Python =3.9 scipy=0.15.0 numpy

Note:For more information on the conda command line, you can readConda environments.

Additional notes:

  • If you create a new conda environment while VS Code is running, use the refresh icon on the top right of thePython: Select Interpreterwindow; otherwise you may not find the environment there.

    Conda environment refresh icon

  • To ensure the environment is properly set up from a shell perspective, use an Anaconda prompt and activate the desired environment. Then, you can launch VS Code by entering thecode.command. Once VS Code is open, you can select the interpreter either by using the Command Palette or by clicking on the status bar.

  • Although the Python extension for VS Code doesn't currently have direct integration with condaenvironment.ymlfiles, VS Code itself is a great YAML editor.

  • Conda environments can't be automatically activated in the VS Code Integrated Terminal if the default shell is set to PowerShell. To change the shell, seeIntegrated terminal - Terminal profiles.

  • You can manually specify the path to thecondaexecutable to use for activation (version 4.4+). To do so, open the Command Palette (⇧⌘P(Windows, LinuxCtrl+Shift+P)) and runPreferences: Open User Settings.Then setPython.condaPath,which is in the Python extension section of User Settings, with the appropriate path.

Working with Python interpreters

Select and activate an environment

The Python extension tries to find and then select what it deems the best environment for the workspace. If you would prefer to select a specific environment, use thePython: Select Interpretercommand from theCommand Palette(⇧⌘P(Windows, LinuxCtrl+Shift+P)).

Python: Select Interpreter command

Note:If the Python extension doesn't find an interpreter, it issues a warning. On macOS 12.2 and older, the extension also issues a warning if you're using the OS-installed Python interpreter as it is known to have compatibility issues. In either case, you can disable these warnings by settingPython.disableInstallationChecktotruein your usersettings.

ThePython: Select Interpretercommand displays a list of available global environments, conda environments, and virtual environments. (See theWhere the extension looks for environmentssection for details, including the distinctions between these types of environments.) The following image, for example, shows several Anaconda and CPython installations along with a conda environment and a virtual environment (env) that's located within the workspace folder:

List of interpreters

Note:On Windows, it can take a little time for VS Code to detect available conda environments. During that process, you may see "(cached)" before the path to an environment. The label indicates that VS Code is presently working with cached information for that environment.

If you have a folder or a workspace open in VS Code and you select an interpreter from the list, the Python extension will store that information internally. This ensures that the same interpreter will be used when you reopen the workspace.

The selected environment is used by the Python extension for running Python code (using thePython: Run Python File in Terminalcommand), providing language services (auto-complete, syntax checking, linting, formatting, etc.) when you have a.pyfile open in the editor, and opening a terminal with theTerminal: Create New Terminalcommand. In the latter case, VS Code automatically activates the selected environment.

Tip:To prevent automatic activation of a selected environment, add"Python.terminal.activateEnvironment": falseto yoursettings.jsonfile (it can be placed anywhere as a sibling to the existing settings).

Tip:If the activate command generates the message "Activate.ps1 is not digitally signed. You cannot run this script on the current system.", then you need to temporarily change the PowerShell execution policy to allow scripts to run (seeAbout Execution Policiesin the PowerShell documentation): Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process

Note:By default, VS Code uses the interpreter selected for your workspace when debugging code. You can override this behavior by specifying a different path in thePythonproperty of a debug configuration. SeeChoose a debugging environment.

The selected interpreter version will show on the right side of the Status Bar.

Status Bar showing a selected interpreter

The Status Bar also reflects when no interpreter is selected.

Status bar showing no selected Python interpreter

In either case, clicking this area of the Status Bar is a convenient shortcut for thePython: Select Interpretercommand.

Tip:If you have any problems with VS Code recognizing a virtual environment, pleasefile an issueso we can help determine the cause.

Manually specify an interpreter

If VS Code doesn't automatically locate an interpreter you want to use, you can browse for the interpreter on your file system or provide the path to it manually.

You can do so by running thePython: Select Interpretercommand and select theEnter interpreter path...option that shows on the top of the interpreters list:

Enter interpreter path option on the interpreters list

You can then either enter the full path of the Python interpreter directly in the text box (for example, ".venv/Scripts/ Python.exe" ), or you can select theFind...button and browse your file system to find the Python executable you wish to select.

Enter path or browse for an interpreter

If you want to manually specify a default interpreter that will be used when you first open your workspace, you can create or modify an entry for thePython.defaultInterpreterPathsetting.

Note:Changes to thePython.defaultInterpreterPathsetting are not picked up after an interpreter has already been selected for a workspace; any changes to the setting will be ignored once an initial interpreter is selected for the workspace.

Additionally, if you'd like to set up a default interpreter to all of your Python applications, you can add an entry forPython.defaultInterpreterPathmanually inside your User Settings. To do so, open the Command Palette (⇧⌘P(Windows, LinuxCtrl+Shift+P)) and enterPreferences: Open User Settings.Then setPython.defaultInterpreterPath,which is in the Python extension section of User Settings, with the appropriate interpreter.

How the extension chooses an environment automatically

If an interpreter hasn't been specified, then the Python extension automatically selects the interpreter with the highest version in the following priority order:

  1. Virtual environments located directly under the workspace folder.
  2. Virtual environments related to the workspace but stored globally. For example,PipenvorPoetryenvironments that are located outside of the workspace folder.
  3. Globally installed interpreters. For example, the ones found in/usr/local/bin,C:\\ Python 38,etc.

Note:The interpreter selected may differ from whatPythonrefers to in your terminal.

If Visual Studio Code doesn't locate your interpreter automatically, you canmanually specify an interpreter.

Where the extension looks for environments

The extension automatically looks for interpreters in the following locations, in no particular order:

  • Standard install paths such as/usr/local/bin,/usr/sbin,/sbin,c:\\ Python 36,etc.
  • Virtual environments located directly under the workspace (project) folder.
  • Virtual environments located in the folder identified by thePython.venvPathsetting (seeGeneral Python settings), which can contain multiple virtual environments. The extension looks for virtual environments in the first-level subfolders ofvenvPath.
  • Virtual environments located in a~/.virtualenvsfolder forvirtualenvwrapper.
  • Interpreters created bypyenv,Pipenv,andPoetry.
  • Virtual environments located in the path identified byWORKON_HOME(as used byvirtualenvwrapper).
  • Conda environments found byconda env list.Conda environments which do not have an interpreter will have one installed for them upon selection.
  • Interpreters installed in a.direnvfolder fordirenvunder the workspace folder.

Environments and Terminal windows

After usingPython: Select Interpreter,that interpreter is applied when right-clicking a file and selectingPython: Run Python File in Terminal.The environment is also activated automatically when you use theTerminal: Create New Terminalcommand unless you change thePython.terminal.activateEnvironmentsetting tofalse.

Please note that launching VS Code from a shell in which a specific Python environment is activated doesn't automatically activate that environment in the default Integrated Terminal.

Note:conda environments cannot be automatically activated in the integrated terminal if PowerShell is set as the integrated shell. SeeIntegrated terminal - Terminal profilesfor how to change the shell.

Changing interpreters with thePython: Select Interpretercommand doesn't affect terminal panels that are already open. Thus, you can activate separate environments in a split terminal: select the first interpreter, create a terminal for it, select a different interpreter, then use the split button (⌘\(Windows, LinuxCtrl+Shift+5)) in the terminal title bar.

Choose a debugging environment

By default, the debugger will use the Python interpreter chosen with the Python extension. However, if there is aPythonproperty specified in the debug configuration oflaunch.json,it takes precedence. If this property is not defined, it will fall back to using the Python interpreter path selected for the workspace.

For more details on debug configuration, seeDebugging configurations.

Environment variables

Environment variable definitions file

An environment variable definitions file is a text file containing key-value pairs in the form ofenvironment_variable=value,with#used for comments. Multiline values aren't supported, but references to previously defined environment variables are allowed. Environment variable definitions files can be used for scenarios such as debugging and tool execution (including linters, formatters, IntelliSense, and testing tools), but aren't applied to the terminal.

Note:Environment variable definitions files are not necessarily cross-platform. For instance, while Unix uses:as a path separator in environment variables, Windows uses;.There is no normalization of such operating system differences, and so you need to make sure any environment definitions file use values that are compatible with your operating system.

By default, the Python extension looks for and loads a file named.envin the current workspace folder, then applies those definitions. The file is identified by the default entry"Python.envFile": "${workspaceFolder}/.env"in your user settings (seeGeneral Python settings). You can change thePython.envFilesetting at any time to use a different definitions file.

Note:Environment variable definitions files are not used in all situations where environment variables are available for use. Unless Visual Studio Code documentation states otherwise, these only affect certain scenarios as per their definition. For example, the extension doesn't use environment variable definitions files when resolving setting values.

A debug configuration also contains anenvFileproperty that also defaults to the.envfile in the current workspace (seeDebugging - Set configuration options). This property allows you to easily set variables for debugging purposes that replace variables specified in the default.envfile.

For example, when developing a web application, you might want to easily switch between development and production servers. Instead of coding the different URLs and other settings into your application directly, you could use separate definitions files for each. For example:

dev.env file

# dev.env - development configuration

# API endpoint
MYPROJECT_APIENDPOINT=https://my.domain /api/dev/

# Variables for the database
MYPROJECT_DBURL=https://my.domain /db/dev
MYPROJECT_DBUSER=devadmin
MYPROJECT_DBPASSWORD=!dfka**213=

prod.env file

# prod.env - production configuration

# API endpoint
MYPROJECT_APIENDPOINT=https://my.domain /api/

# Variables for the database
MYPROJECT_DBURL=https://my.domain /db/
MYPROJECT_DBUSER=coreuser
MYPROJECT_DBPASSWORD=kKKfa98*11@

You can then set thePython.envFilesetting to${workspaceFolder}/prod.env,then set theenvFileproperty in the debug configuration to${workspaceFolder}/dev.env.

Note:When environment variables are specified using multiple methods, be aware that there is an order of precedence. Allenvvariables defined in thelaunch.jsonfile will override variables contained in the.envfile, specified by thePython.envFilesetting (user or workspace). Similarly,envvariables defined in thelaunch.jsonfile will override the environment variables defined in theenvFilethat are specified inlaunch.json.

Use of the PYTHONPATH variable

ThePYTHONPATHenvironment variable specifies additional locations where the Python interpreter should look for modules. In VS Code, PYTHONPATH can be set through the terminal settings (terminal.integrated.env.*) and/or within an.envfile.

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 won't have an effect on module look-up.

Next steps

  • Editing code- Learn about autocomplete, IntelliSense, formatting, and refactoring for Python.
  • Debugging- Learn to debug Python both locally and remotely.
  • Testing- Configure test environments and discover, run, and debug tests.
  • Settings reference- Explore the full range of Python-related settings in VS Code.

More Python resources