Visual Studio Code And Python



Start Python interactive mode to run Python code one line at a time. Install Visual Studio Code, Python, and the Python extension for Visual Studio Code on your computer. Create a Python script file and write Python code in Visual Studio Code. Run your Python script file. Setup Visual Studio Code for Python Summary: in this tutorial, you’ll learn how to use set up Visual Studio Code for Python. Visual Studio Code is a lightweight source code editor. The Visual Studio Code is often called VS Code. Python in Visual Studio Code. Working with Python in Visual Studio Code, using the Microsoft Python extension, is simple, fun, and productive. The extension makes VS Code an excellent Python editor, and works on any operating system with a variety of Python interpreters. It leverages all of VS Code's power to provide auto complete and IntelliSense, linting, debugging, and unit testing, along with the ability to easily switch between Python. Jul 01, 2020 Alternatively, you can also hit the Extensions icon in the left-hand pane inside Visual Studio Code and search for the keyword “ python ”. Select the extension which is provided by Microsoft and click on Install. I have already installed the extension on my machine: Figure 7 – Search and Install the Python extension for VS Code. Python support is presently available only on Visual Studio for Windows; on Mac and Linux, Python support is available through Visual Studio Code. Download and run the latest Visual Studio installer for Windows (Python support is present in release 15.2 and later).

Is cisco anyconnect free

-->

A Python environment is a context in which you run Python code and includes global, virtual, and conda environments. An environment consists of an interpreter, a library (typically the Python Standard Library), and a set of installed packages. These components together determine which language constructs and syntax are valid, what operating-system functionality you can access, and which packages you can use.

In Visual Studio on Windows, you use the Python Environments window, as described in this article, to manage environments and select one as the default for new projects. Other aspects of environments are found in the following articles:

Python In Visual Studio

  • For any given project, you can select a specific environment rather than use the default.

  • For details on creating and using virtual environments for Python projects, see Use virtual environments.

  • If you want to install packages in an environment, refer to the Packages tab reference.

  • To install another Python interpreter, see Install Python interpreters. In general, if you download and run an installer for a mainline Python distribution, Visual Studio detects that new installation and the environment appears in the Python Environments window and can be selected for projects.

If you're new to Python in Visual Studio, the following articles also provide from general background:

Note

You can't manage environments for Python code that is opened only as a folder using the File > Open > Folder command. Instead, Create a Python project from existing code to enjoy the environment features of Visual Studio.

Note

You can manage environments for Python code that is opened as a folder using the File > Open > Folder command. The Python toolbar allows you switch between all detected environments, and also add a new environment. The environment information is stored in the PythonSettings.json file in the Workspace .vs folder.

The Python Environments window

The environments that Visual Studio knows about are displayed in the Python Environments window. To open the window, use one of the following methods:

  • Select the View > Other Windows > Python Environments menu command.

  • Right-click the Python Environments node for a project in Solution Explorer and select View All Python Environments:

In either case, the Python Environments window appears alongside Solution Explorer:

Visual Studio looks for installed global environments using the registry (following PEP 514), along with virtual environments and conda environments (see Types of environments). If you don't see an expected environment in the list, see Manually identify an existing environment.

When you select an environment in the list, Visual Studio displays various properties and commands for that environment on the Overview tab. For example, you can see in the image above that the interpreter's location is C:Python36-32. The four commands at the bottom of the Overview tab each open a command prompt with the interpreter running. For more information, see Python Environments window tab reference - Overview.

Use the drop-down list below the list of environments to switch to different tabs such as Packages, and IntelliSense. These tabs are also described in the Python Environments window tab reference.

Selecting an environment doesn't change its relation to any projects. The default environment, shown in boldface in the list, is the one that Visual Studio uses for any new projects. To use a different environment with new projects, use the Make this the default environment for new projects command. Within the context of a project you can always select a specific environment. For more information, see Select an environment for a project.

To the right of each listed environment is a control that opens an Interactive window for that environment. (In Visual Studio 2017 15.5 and earlier, another control appears that refreshes the IntelliSense database for that environment. See Environments window tab reference for details about the database.)

Tip

When you expand the Python Environments window wide enough, you get a fuller view of your environments that you may find more convenient to work with.

Tip

When you expand the Python Environments window wide enough, you get a fuller view of your environments that you may find more convenient to work with.

Note

Although Visual Studio respects the system-site-packages option, it doesn't provide a way to change it from within Visual Studio.

What if no environments appear?

If no environments appear, it means Visual Studio failed to detect any Python installations in standard locations. For example, you may have installed Visual Studio 2017 or later but cleared all the interpreter options in the installer options for the Python workload. Similarly, you may have installed Visual Studio 2015 or earlier but did not install an interpreter manually (see Install Python interpreters).

If you know you have a Python interpreter on your computer but Visual Studio (any version) did not detect it, then use the + Custom command to specify its location manually. See the next section, Manually identify an existing environment.

Tip

Visual Studio detects updates to an existing interpreter, such as upgrading Python 2.7.11 to 2.7.14 using the installers from python.org. During the installation process, the older environment disappears from the Python Environments list before the update appears in its place.

However, if you manually move an interpreter and its environment using the file system, Visual Studio won't know the new location. For more information, see Move an interpreter.

Quick quotes

Visual Studio Code And Python

Types of environments

Visual Studio can work with global, virtual, and conda environments.

Global environments

Each Python installation (for example, Python 2.7, Python 3.6, Python 3.7, Anaconda 4.4.0, etc., see Install Python interpreters) maintains its own global environment. Each environment is composed of the specific Python interpreter, its standard library, a set of pre-installed packages, and any additional packages you install while that environment is activated. Installing a package into a global environment makes it available to all projects using that environment. If the environment is located in a protected area of the file system (within c:program files, for example), then installing packages requires administrator privileges.

Global environments are available to all projects on the computer. In Visual Studio, you select one global environment as the default, which is used for all projects unless you specifically choose a different one for a project. For more information, see Select an environment for a project.

Virtual environments

Although working in a global environment is an easy way to get started, that environment will, over time, become cluttered with many different packages that you've installed for different projects. Such clutter makes it difficult to thoroughly test an application against a specific set of packages with known versions, which is exactly the kind of environment you'd set up on a build server or web server. Conflicts can also occur when two projects require incompatible packages or different versions of the same package.

For this reason, developers often create a virtual environment for a project. A virtual environment is a subfolder in a project that contains a copy of a specific interpreter. When you activate the virtual environment, any packages you install are installed only in that environment's subfolder. When you then run a Python program within that environment, you know that it's running against only those specific packages.

Visual Studio provides direct support for creating a virtual environment for a project. For example, if you open a project that contains a requirements.txt, or create a project from a template that includes that file, Visual Studio prompts you to automatically create a virtual environment and install those dependencies.

At any time within an open project, you can create a new virtual environment. In Solution Explorer, expand the project node, right-click Python Environments, and select 'Add Virtual Environment.' For more information, see Create a virtual environment.

Visual Studio also provides a command to generate a requirements.txt file from a virtual environment, making it easy to recreate the environment on other computers. For more information, see Use virtual environments.

Visual studio code python tutorial

Conda environments

A conda environment is one created using the conda tool, or with integrated conda management in Visual Studio 2017 version 15.7 and higher. (Requires Anaconda or Miniconda, which are available through the Visual Studio installer, see Installation.)

  1. Select + Create conda environment in the Python Environments window, which opens a Create new conda environment tab:

  2. Enter a name for the environment in the Name field, select a base Python interpreter in the Python field, and select Create.

  3. The Output window shows progress for the new environment, with a few CLI instructions once creation is complete:

  4. Within Visual Studio, you can activate a conda environment for a project as you would any other environment as described on Select an environment for a project.

  5. To install packages in the environment, use the Packages tab.

  1. Select + Add Environment in the Python Environments window (or from the Python toolbar), which opens the Add environment dialog box. In that dialog, select the Conda environment tab:

  2. Configure the following fields:

    FieldDescription
    ProjectThe project in which to create the environment (if you have multiple projects in the same Visual Studio solution).
    NameThe name for the conda environment.
    Add packages fromChoose Environment file if you have an environment.yml file describing your dependencies, or choose One or more Anaconda package names and list at least one Python package or a Python version in the field below. The package list instructs conda to create a Python environment. To install the latest version of Python, use python; to install a specific version, use python=,major>.<minor> as in python=3.7. You can also use the package button to select Python versions and common packages from a series of menus.
    Set as current environmentActivates the new environment in the selected project after the environment is created.
    Set as default environment for new projectsAutomatically sets and activates the conda environment in any new projects created in Visual Studio. This option is the same as using the Make this the default environment for new projects in the Python Environments window.
    View in Python Environments windowSpecifies whether to show the Python Environments window after creating the environment.

    Important

    When creating a conda environment, be sure to specify at least one Python version or Python package using either environments.yml or the package list, which ensures that the environment contains a Python runtime. Otherwise, Visual Studio ignores the environment: the environment doesn't appear anywhere the Python Environments window, isn't be set as the current environment for a project, and isn't available as a global environment.

    If you happen to create a conda environment without a Python version, use the conda info command to see the locations of conda environment folders, then manually remove the subfolder for the environment from that location.

  3. Select Create, and observe progress in the Output window. The output includes with a few CLI instructions once creation is complete:

  4. Within Visual Studio, you can activate a conda environment for a project as you would any other environment as described on Select an environment for a project.

  5. To install additional packages in the environment, use the Packages tab.

Note

For best results with conda environments, use conda 4.4.8 or later (conda versions are different from Anaconda versions). You can install suitable versions of Miniconda (Visual Studio 2019) and Anaconda (Visual Studio 2017) through the Visual Studio installer.

To see the conda version, where conda environments are stored, and other information, run conda info at an Anaconda command prompt (that is, a command prompt where Anaconda is in the path):

Your conda environment folders appear as follows:

Because conda environments are not stored with a project, they act similarly to global environments. For example, installing a new package into a conda environment makes that package available to all projects using that environment.

For Visual Studio 2017 version 15.6 and earlier, you can use conda environments by pointing to them manually as described under Manually identify an existing environment.

Visual Studio 2017 version 15.7 and later detects conda environments automatically and displays them in the Python Environments window as described in the next section.

Manually identify an existing environment

Use the following steps to identify an environment that's installed in a non-standard location (including conda environments in Visual Studio 2017 version 15.6 and earlier):

  1. Select + Custom in the Python Environments window, which opens the Configure tab:

  2. Enter a name for the environment in the Description field.

  3. Enter or browse (using ..) to the path of the interpreter in the Prefix path field.

  4. If Visual Studio detects a Python interpreter at that location (such as the path shown below for a conda environment), it enables the Auto Detect command. Selecting Auto Detect completes the remaining fields. You can also complete those fields manually.

  5. Once the fields contain the values you want, select Apply to save the configuration. You can now use the environment like any other within Visual Studio.

  6. If you need to remove a manually identified environment, select the Remove command on the Configure tab. Auto-detected environments do not provide this option. For more information, see Configure tab.

  1. Select + Add Environment in the Python Environments window (or from the Python toolbar), which opens the Add environment dialog box. In that dialog, select the Existing environment tab:

  2. Select the Environment drop-down, then select Custom:

  3. In the provided fields in the dialog box, enter or browse (using ..) to the path of the interpreter under Prefix path, which fills in most of the other fields. After reviewing those values and modifying as necessary, select Add.

  4. Details of the environment can be reviewed and modified at any time in the Python Environments window. In that window, select the environment, then select the Configure tab. After making changes, select the Apply command. You can also remove the environment using the Remove command (not available for auto-detected environments). For more information, see Configure tab.

Fix or delete invalid environments

If Visual Studio finds registry entries for an environment, but the path to the interpreter is invalid, then the Python Environments window shows the name with a strikeout font:

Visual Studio Code And Python Virtualenv

Getting

Vs Code Python Intellisense

To correct an environment you wish to keep, first try using its installer's Repair process. The installers for standard Python 3.x, for example, include that option.

To correct an environment that doesn't have a repair option, or to remove an invalid environment, use the following steps to modify the registry directly. Visual Studio automatically updates the Python Environments window when you make changes to the registry.

  1. Run regedit.exe.

  2. Navigate to HKEY_LOCAL_MACHINESOFTWAREPython or HKEY_CURRENT_USERSOFTWAREPython. For IronPython, look for IronPython instead.

  3. Expand the node that matches the distribution, such as Python Core for CPython or ContinuumAnalytics for Anaconda. For IronPython, expand the version number node.

  4. Inspect the values under the InstallPath node:

    • If the environment still exists on your computer, change the value of ExecutablePath to the correct location. Also correct the (Default) and WindowedExecutablePath values as necessary.
    • If the environment no longer exists on your computer and you want to remove it from the Python Environments window, delete the parent node of InstallPath, such as 3.6 in the image above.
    • Invalid settings in HKEY_CURRENT_USERSOFTWAREPython override the settings in HKEY_LOCAL_MACHINESOFTWAREPython

See also

Working with Python in Visual Studio Code, using the Microsoft Python extension, is simple, fun, and productive. The extension makes VS Code an excellent Python editor, and works on any operating system with a variety of Python interpreters. It leverages all of VS Code's power to provide auto complete and IntelliSense, linting, debugging, and unit testing, along with the ability to easily switch between Python environments, including virtual and conda environments.

This article provides only an overview of the different capabilities of the Python extension for VS Code. For a walkthrough of editing, running, and debugging code, use the button below.

Install Python and the Python extension

The tutorial guides you through installing Python and using the extension. You must install a Python interpreter yourself separately from the extension. For a quick install, use Python 3.7 from python.org and install the extension from the VS Code Marketplace.

Once you have a version of Python installed, activate it using the Python: Select Interpreter command. If VS Code doesn't automatically locate the interpreter you're looking for, refer to Environments - Manually specify an interpreter.

You can configure the Python extension through settings. Learn more in the Python Settings reference.

Python download for vs code

Windows Subsystem for Linux: If you are on Windows, WSL is a great way to do Python development. You can run Linux distributions on Windows and Python is often already installed. When coupled with the Remote - WSL extension, you get full VS Code editing and debugging support while running in the context of WSL. To learn more, go to Developing in WSL or try the Working in WSL tutorial.

Insiders program

The Insiders program allows you to try out and automatically install new versions of the Python extension prior to release, including new features and fixes.

If you'd like to opt into the program, you can either open the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)) and select Python: Switch to Insiders Daily/Weekly Channel or else you can open settings (⌘, (Windows, Linux Ctrl+,)) and look for Python: Insiders Channel to set the channel to 'daily' or 'weekly'.

Run Python code

To experience Python, create a file (using the File Explorer) named hello.py and paste in the following code (assuming Python 3):

The Python extension then provides shortcuts to run Python code in the currently selected interpreter (Python: Select Interpreter in the Command Palette):

Python On Vs Code

  • In the text editor: right-click anywhere in the editor and select Run Python File in Terminal. If invoked on a selection, only that selection is run.
  • In Explorer: right-click a Python file and select Run Python File in Terminal.

You can also use the Terminal: Create New Integrated Terminal command to create a terminal in which VS Code automatically activates the currently selected interpreter. See Environments below. The Python: Start REPL activates a terminal with the currently selected interpreter and then runs the Python REPL.

For a more specific walkthrough on running code, see the tutorial.

Autocomplete and IntelliSense

The Python extension supports code completion and IntelliSense using the currently selected interpreter. IntelliSense is a general term for a number of features, including intelligent code completion (in-context method and variable suggestions) across all your files and for built-in and third-party modules.

IntelliSense quickly shows methods, class members, and documentation as you type, and you can trigger completions at any time with ⌃Space (Windows, Linux Ctrl+Space). You can also hover over identifiers for more information about them.

Tip: Check out the IntelliCode extension for VS Code (preview). IntelliCode provides a set of AI-assisted capabilities for IntelliSense in Python, such as inferring the most relevant auto-completions based on the current code context.

Linting

Linting analyzes your Python code for potential errors, making it easy to navigate to and correct different problems.

The Python extension can apply a number of different linters including Pylint, pycodestyle, Flake8, mypy, pydocstyle, prospector, and pylama. See Linting.

Debugging

No more print statement debugging! Set breakpoints, inspect data, and use the debug console as you run your program step by step. Debug a number of different types of Python applications, including multi-threaded, web, and remote applications.

Code

For Python-specific details, including setting up your launch.json configuration and remote debugging, see Debugging. General VS Code debugging information is found in the debugging document. The Django and Flask tutorials also demonstrate debugging in the context of those web apps, including debugging Django page templates.

Environments

The Python extension automatically detects Python interpreters that are installed in standard locations. It also detects conda environments as well as virtual environments in the workspace folder. See Configuring Python environments. You can also use the python.pythonPath setting to point to an interpreter anywhere on your computer.

The current environment is shown on the left side of the VS Code Status Bar:

The Status Bar also indicates if no interpreter is selected:

The selected environment is used for IntelliSense, auto-completions, linting, formatting, and any other language-related feature other than debugging. It is also activated when you use run Python in a terminal.

To change the current interpreter, which includes switching to conda or virtual environments, select the interpreter name on the Status Bar or use the Python: Select Interpreter command.

VS Code prompts you with a list of detected environments as well as any you've added manually to your user settings (see Configuring Python environments).

Installing packages

Packages are installed using the Terminal panel and commands like pip install <package_name> (Windows) and pip3 install <package_name> (macOS/Linux). VS Code installs that package into your project along with its dependencies. Examples are given in the Python tutorial as well as the Django and Flask tutorials.

Jupyter notebooks

If you open a Jupyter notebook file (.ipynb) in VS Code, you can use the Jupyter Notebook Editor to directly view, modify, and run code cells.

You can also convert and open the notebook as a Python code file. The notebook's cells are delimited in the Python file with #%% comments, and the Python extension shows Run Cell or Run All Cells CodeLens. Selecting either CodeLens starts the Jupyter server and runs the cell(s) in the Python interactive window:

Visual Studio Code And Python Interview

Opening a notebook as a Python file allows you to use all of VS Code's debugging capabilities. You can then save the notebook file and open it again as a notebook in the Notebook Editor, Jupyter, or even upload it to a service like Azure Notebooks.

Using either method, Notebook Editor or a Python file, you can also connect to a remote Jupyter server for running the code. For more information, see Jupyter support.

Testing

The Python extension supports testing with the unittest, pytest, and nose test frameworks.

Visual Studio Code And Python Free

To run tests, you enable one of the frameworks in settings. Each framework also has specific settings, such as arguments that identify paths and patterns for test discovery.

Once discovered, VS Code provides a variety of commands (on the Status Bar, the Command Palette, and elsewhere) to run and debug tests, including the ability to run individual test files and individual methods.

Configuration

The Python extension provides a wide variety of settings for its various features. These are described on their relevant topics, such as Editing code, Linting, Debugging, and Testing. The complete list is found in the Settings reference.

Other popular Python extensions

The Microsoft Python extension provides all of the features described previously in this article. Additional Python language support can be added to VS Code by installing other popular Python extensions.

  1. Open the Extensions view (⇧⌘X (Windows, Linux Ctrl+Shift+X)).
  2. Filter the extension list by typing 'python'.

The extensions shown above are dynamically queried. Click on an extension tile above to read the description and reviews to decide which extension is best for you. See more in the Marketplace.

Next steps

  • Python Hello World tutorial - Get started with Python in VS Code.
  • Editing Python - Learn about auto-completion, formatting, and refactoring for Python.
  • Basic Editing - Learn about the powerful VS Code editor.
  • Code Navigation - Move quickly through your source code.
03/07/2019




Comments are closed.