Visual studio code python установка на windows

A Python hello world tutorial using the Python extension in Visual Studio Code (a great Python IDE like PyCharm, if not the best Python IDE)

Getting Started with Python in VS Code

In this tutorial, you will use Python 3 to create the simplest Python «Hello World» application in Visual Studio Code. By using the Python extension, you make VS Code into a great lightweight Python IDE (which you may find a productive alternative to PyCharm).

This tutorial introduces you to VS Code as a Python environment — primarily how to edit, run, and debug code through the following tasks:

  • Write, run, and debug a Python «Hello World» Application
  • Learn how to install packages by creating Python virtual environments
  • Write a simple Python script to plot figures within VS Code

This tutorial is not intended to teach you Python itself. Once you are familiar with the basics of VS Code, you can then follow any of the programming tutorials on python.org within the context of VS Code for an introduction to the language.

If you have any problems, you can search for answers or ask a question on the Python extension Discussions Q&A.

Prerequisites

To successfully complete this tutorial, you need to first setup your Python development environment. Specifically, this tutorial requires:

  • Python 3
  • VS Code application
  • VS Code Python extension

Install Visual Studio Code and the Python Extension

  1. If you have not already done so, install VS Code.

  2. Next, install the Python extension for VS Code from the Visual Studio Marketplace. For additional details on installing extensions, see Extension Marketplace. The Python extension is named Python and it’s published by Microsoft.

    Python extension on Marketplace

Install a Python interpreter

Along with the Python extension, you need to install a Python interpreter. Which interpreter you use is dependent on your specific needs, but some guidance is provided below.

Windows

Install Python from python.org. You can typically use the Download Python button that appears first on the page to download the latest version.

Note: If you don’t have admin access, an additional option for installing Python on Windows is to use the Microsoft Store. The Microsoft Store provides installs of supported Python versions.

For additional information about using Python on Windows, see Using Python on Windows at Python.org

macOS

The system install of Python on macOS is not supported. Instead, a package management system like Homebrew is recommended. To install Python using Homebrew on macOS use brew install python3 at the Terminal prompt.

Note On macOS, make sure the location of your VS Code installation is included in your PATH environment variable. See these setup instructions for more information.

Linux

The built-in Python 3 installation on Linux works well, but to install other Python packages you must install pip with get-pip.py.

Other options

  • Data Science: If your primary purpose for using Python is Data Science, then you might consider a download from Anaconda. Anaconda provides not just a Python interpreter, but many useful libraries and tools for data science.

  • Windows Subsystem for Linux: If you are working on Windows and want a Linux environment for working with Python, the Windows Subsystem for Linux (WSL) is an option for you. If you choose this option, you’ll also want to install the WSL extension. For more information about using WSL with VS Code, see VS Code Remote Development or try the Working in WSL tutorial, which will walk you through setting up WSL, installing Python, and creating a Hello World application running in WSL.

Verify the Python installation

To verify that you’ve installed Python successfully on your machine, run one of the following commands (depending on your operating system):

  • Linux/macOS: open a Terminal Window and type the following command:

    python3 --version
    
  • Windows: open a command prompt and run the following command:

    py -3 --version
    

If the installation was successful, the output window should show the version of Python that you installed.

Note You can use the py -0 command in the VS Code integrated terminal to view the versions of python installed on your machine. The default interpreter is identified by an asterisk (*).

Start VS Code in a workspace folder

By starting VS Code in a folder, that folder becomes your «workspace». VS Code stores settings that are specific to that workspace in .vscode/settings.json, which are separate from user settings that are stored globally.

Using a command prompt or terminal, create an empty folder called «hello», navigate into it, and open VS Code (code) in that folder (.) by entering the following commands:

mkdir hello
cd hello
code .

Note: If you’re using an Anaconda distribution, be sure to use an Anaconda command prompt.

Alternately, you can run VS Code through the operating system UI, then use File > Open Folder to open the project folder.

Select a Python interpreter

Python is an interpreted language. Thus, in order to run Python code and get Python IntelliSense, you must tell VS Code which interpreter to use.

From within VS Code, select a Python 3 interpreter by opening the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)), start typing the Python: Select Interpreter command to search, then select the command. You can also use the Select Python Environment option on the Status Bar if available (it may already show a selected interpreter, too):

No interpreter selected

The command presents a list of available interpreters that VS Code can find automatically, including virtual environments. If you don’t see the desired interpreter, see Configuring Python environments.

Select an Interpreter

Note: When using an Anaconda distribution, the correct interpreter should have the suffix ('base':conda), for example Python 3.7.3 64-bit ('base':conda).

Selecting an interpreter sets which interpreter will be used by the Python extension for that workspace.

Note: If you select an interpreter without a workspace folder open, VS Code sets python.defaultInterpreterPath in User scope instead, which sets the default interpreter for VS Code in general. The user setting makes sure you always have a default interpreter for Python projects. The workspace settings lets you override the user setting.

Create a Python Hello World source code file

From the File Explorer toolbar, select the New File button on the hello folder:

File Explorer New File

Name the file hello.py, and it automatically opens in the editor:

File Explorer hello.py

By using the .py file extension, you tell VS Code to interpret this file as a Python program, so that it evaluates the contents with the Python extension and the selected interpreter.

Note: The File Explorer toolbar also allows you to create folders within your workspace to better organize your code. You can use the New folder button to quickly create a folder.

Now that you have a code file in your Workspace, enter the following source code in hello.py:

msg = "Hello World"
print(msg)

When you start typing print, notice how IntelliSense presents auto-completion options.

IntelliSense appearing for Python code

IntelliSense and auto-completions work for standard Python modules as well as other packages you’ve installed into the environment of the selected Python interpreter. It also provides completions for methods available on object types. For example, because the msg variable contains a string, IntelliSense provides string methods when you type msg.:

IntelliSense appearing for a variable whose type provides methods

Feel free to experiment with IntelliSense some more, but then revert your changes so you have only the msg variable and the print call, and save the file (⌘S (Windows, Linux Ctrl+S)).

For full details on editing, formatting, and refactoring, see Editing code. The Python extension also has full support for Linting.

Run Hello World

It’s simple to run hello.py with Python. Just click the Run Python File in Terminal play button in the top-right side of the editor.

Using the run python file in terminal button

The button opens a terminal panel in which your Python interpreter is automatically activated, then runs python3 hello.py (macOS/Linux) or python hello.py (Windows):

Program output in a Python terminal

There are three other ways you can run Python code within VS Code:

  • Right-click anywhere in the editor window and select Run Python File in Terminal (which saves the file automatically):

    Run Python File in Terminal command in the Python editor

  • Select one or more lines, then press Shift+Enter or right-click and select Run Selection/Line in Python Terminal. This command is convenient for testing just a part of a file.

  • From the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)), select the Python: Start REPL command to open a REPL terminal for the currently selected Python interpreter. In the REPL, you can then enter and run lines of code one at a time.

Configure and run the debugger

Let’s now try debugging our simple Hello World program.

First, set a breakpoint on line 2 of hello.py by placing the cursor on the print call and pressing F9. Alternately, just click in the editor’s left gutter, next to the line numbers. When you set a breakpoint, a red circle appears in the gutter.

Setting a breakpoint in hello.py

Next, to initialize the debugger, press F5. Since this is your first time debugging this file, a configuration menu will open from the Command Palette allowing you to select the type of debug configuration you would like for the opened file.

Debug configurations after launch.json is created

Note: VS Code uses JSON files for all of its various configurations; launch.json is the standard name for a file containing debugging configurations.

These different configurations are fully explained in Debugging configurations; for now, just select Python File, which is the configuration that runs the current file shown in the editor using the currently selected Python interpreter.

You can also start the debugger by clicking on the down-arrow next to the run button on the editor, and selecting Debug Python File in Terminal.

Using the debug Python file in terminal button

The debugger will stop at the first line of the file breakpoint. The current line is indicated with a yellow arrow in the left margin. If you examine the Local variables window at this point, you will see now defined msg variable appears in the Local pane.

Debugging step 2 - variable defined

A debug toolbar appears along the top with the following commands from left to right: continue (F5), step over (F10), step into (F11), step out (⇧F11 (Windows, Linux Shift+F11)), restart (⇧⌘F5 (Windows, Linux Ctrl+Shift+F5)), and stop (⇧F5 (Windows, Linux Shift+F5)).

Debugging toolbar

The Status Bar also changes color (orange in many themes) to indicate that you’re in debug mode. The Python Debug Console also appears automatically in the lower right panel to show the commands being run, along with the program output.

To continue running the program, select the continue command on the debug toolbar (F5). The debugger runs the program to the end.

Tip Debugging information can also be seen by hovering over code, such as variables. In the case of msg, hovering over the variable will display the string Hello world in a box above the variable.

You can also work with variables in the Debug Console (If you don’t see it, select Debug Console in the lower right area of VS Code, or select it from the menu.) Then try entering the following lines, one by one, at the > prompt at the bottom of the console:

msg
msg.capitalize()
msg.split()

Debugging step 3 - using the debug console

Select the blue Continue button on the toolbar again (or press F5) to run the program to completion. «Hello World» appears in the Python Debug Console if you switch back to it, and VS Code exits debugging mode once the program is complete.

If you restart the debugger, the debugger again stops on the first breakpoint.

To stop running a program before it’s complete, use the red square stop button on the debug toolbar (⇧F5 (Windows, Linux Shift+F5)), or use the Run > Stop debugging menu command.

For full details, see Debugging configurations, which includes notes on how to use a specific Python interpreter for debugging.

Tip: Use Logpoints instead of print statements: Developers often litter source code with print statements to quickly inspect variables without necessarily stepping through each line of code in a debugger. In VS Code, you can instead use Logpoints. A Logpoint is like a breakpoint except that it logs a message to the console and doesn’t stop the program. For more information, see Logpoints in the main VS Code debugging article.

Install and use packages

Let’s now run an example that’s a little more interesting. In Python, packages are how you obtain any number of useful code libraries, typically from PyPI. For this example, you use the matplotlib and numpy packages to create a graphical plot as is commonly done with data science. (Note that matplotlib cannot show graphs when running in the Windows Subsystem for Linux as it lacks the necessary UI support.)

Return to the Explorer view (the top-most icon on the left side, which shows files), create a new file called standardplot.py, and paste in the following source code:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 20, 100)  # Create a list of evenly-spaced numbers over the range
plt.plot(x, np.sin(x))       # Plot the sine of each x point
plt.show()                   # Display the plot

Tip: If you enter the above code by hand, you may find that auto-completions change the names after the as keywords when you press Enter at the end of a line. To avoid this, type a space, then Enter.

Next, try running the file in the debugger using the «Python: Current file» configuration as described in the last section.

Unless you’re using an Anaconda distribution or have previously installed the matplotlib package, you should see the message, «ModuleNotFoundError: No module named ‘matplotlib'». Such a message indicates that the required package isn’t available in your system.

To install the matplotlib package (which also installs numpy as a dependency), stop the debugger and use the Command Palette to run Terminal: Create New Terminal (⌃⇧` (Windows, Linux Ctrl+Shift+`)). This command opens a command prompt for your selected interpreter.

A best practice among Python developers is to avoid installing packages into a global interpreter environment. You instead use a project-specific virtual environment that contains a copy of a global interpreter. Once you activate that environment, any packages you then install are isolated from other environments. Such isolation reduces many complications that can arise from conflicting package versions. To create a virtual environment and install the required packages, enter the following commands as appropriate for your operating system:

Note: For additional information about virtual environments, see Environments.
v

  1. Create a virtual environment using the Create Environment command

    From within VS Code, you can create non-global environments, using Venv or Anaconda, by opening the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)), start typing the Python: Create Environment command to search, and then select the command. You can also trigger the Python: Create Environment command through the Getting Started with Python page.

    The command presents a list of environment types, Venv or Conda. For this example, select Venv.

    Create Environment dropdown

    The command then presents a list of interpreters that can be used for your project.

    Virtual environment interpreter selection

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

    Create environment status notification

    The command will also install necessary packages outlined in a requirements/dependencies file, such as requirements.txt, pyproject.toml, or environment.yml, located in the project folder.

    Note: If you want to create an environment manually, or run into error in the environment creation process, visit the Environments page.

  2. Ensure your new environment is selected by using the Python: Select Interpreter command from the Command Palette.

    Select an Interpreter

  3. Install the packages

    # Don't use with Anaconda distributions because they include matplotlib already.
    
    # macOS
    python3 -m pip install matplotlib
    
    # Windows (may require elevation)
    python -m pip install matplotlib
    
    # Linux (Debian)
    apt-get install python3-tk
    python3 -m pip install matplotlib
    
  4. Rerun the program now (with or without the debugger) and after a few moments a plot window appears with the output:

    matplotlib output

  5. Once you are finished, type deactivate in the terminal window to deactivate the virtual environment.

For additional examples of creating and activating a virtual environment and installing packages, see the Django tutorial and the Flask tutorial.

Next steps

You can configure VS Code to use any Python environment you have installed, including virtual and conda environments. You can also use a separate environment for debugging. For full details, see Environments.

To learn more about the Python language, follow any of the programming tutorials listed on python.org within the context of VS Code.

To learn to build web apps with the Django and Flask frameworks, see the following tutorials:

  • Use Django in Visual Studio Code
  • Use Flask in Visual Studio Code

There is then much more to explore with Python in Visual Studio Code:

  • Editing code — Learn about autocomplete, IntelliSense, formatting, and refactoring for Python.
  • Linting — Enable, configure, and apply a variety of Python linters.
  • 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.
  • Deploy Python to Azure App Service
  • Deploy Python to Container Apps

1/20/2023

Order Area TOCTitle ContentId PageTitle DateApproved MetaDescription MetaSocialImage

1

python

Tutorial

77828f36-ae45-4887-b25c-34545edd52d3

Get Started Tutorial for Python in Visual Studio Code

1/20/2023

A Python hello world tutorial using the Python extension in Visual Studio Code (a great Python IDE like PyCharm, if not the best Python IDE)

images/tutorial/social.png

Getting Started with Python in VS Code

In this tutorial, you will use Python 3 to create the simplest Python «Hello World» application in Visual Studio Code. By using the Python extension, you make VS Code into a great lightweight Python IDE (which you may find a productive alternative to PyCharm).

This tutorial introduces you to VS Code as a Python environment — primarily how to edit, run, and debug code through the following tasks:

  • Write, run, and debug a Python «Hello World» Application
  • Learn how to install packages by creating Python virtual environments
  • Write a simple Python script to plot figures within VS Code

This tutorial is not intended to teach you Python itself. Once you are familiar with the basics of VS Code, you can then follow any of the programming tutorials on python.org within the context of VS Code for an introduction to the language.

If you have any problems, you can search for answers or ask a question on the Python extension Discussions Q&A.

Prerequisites

To successfully complete this tutorial, you need to first setup your Python development environment. Specifically, this tutorial requires:

  • Python 3
  • VS Code application
  • VS Code Python extension

Install Visual Studio Code and the Python Extension

  1. If you have not already done so, install VS Code.

  2. Next, install the Python extension for VS Code from the Visual Studio Marketplace. For additional details on installing extensions, see Extension Marketplace. The Python extension is named Python and it’s published by Microsoft.

    Python extension on Marketplace

Install a Python interpreter

Along with the Python extension, you need to install a Python interpreter. Which interpreter you use is dependent on your specific needs, but some guidance is provided below.

Windows

Install Python from python.org. You can typically use the Download Python button that appears first on the page to download the latest version.

Note: If you don’t have admin access, an additional option for installing Python on Windows is to use the Microsoft Store. The Microsoft Store provides installs of supported Python versions.

For additional information about using Python on Windows, see Using Python on Windows at Python.org

macOS

The system install of Python on macOS is not supported. Instead, a package management system like Homebrew is recommended. To install Python using Homebrew on macOS use brew install python3 at the Terminal prompt.

Note On macOS, make sure the location of your VS Code installation is included in your PATH environment variable. See these setup instructions for more information.

Linux

The built-in Python 3 installation on Linux works well, but to install other Python packages you must install pip with get-pip.py.

Other options

  • Data Science: If your primary purpose for using Python is Data Science, then you might consider a download from Anaconda. Anaconda provides not just a Python interpreter, but many useful libraries and tools for data science.

  • Windows Subsystem for Linux: If you are working on Windows and want a Linux environment for working with Python, the Windows Subsystem for Linux (WSL) is an option for you. If you choose this option, you’ll also want to install the WSL extension. For more information about using WSL with VS Code, see VS Code Remote Development or try the Working in WSL tutorial, which will walk you through setting up WSL, installing Python, and creating a Hello World application running in WSL.

Verify the Python installation

To verify that you’ve installed Python successfully on your machine, run one of the following commands (depending on your operating system):

  • Linux/macOS: open a Terminal Window and type the following command:

  • Windows: open a command prompt and run the following command:

If the installation was successful, the output window should show the version of Python that you installed.

Note You can use the py -0 command in the VS Code integrated terminal to view the versions of python installed on your machine. The default interpreter is identified by an asterisk (*).

Start VS Code in a workspace folder

By starting VS Code in a folder, that folder becomes your «workspace». VS Code stores settings that are specific to that workspace in .vscode/settings.json, which are separate from user settings that are stored globally.

Using a command prompt or terminal, create an empty folder called «hello», navigate into it, and open VS Code (code) in that folder (.) by entering the following commands:

mkdir hello
cd hello
code .

Note: If you’re using an Anaconda distribution, be sure to use an Anaconda command prompt.

Alternately, you can run VS Code through the operating system UI, then use File > Open Folder to open the project folder.

Select a Python interpreter

Python is an interpreted language. Thus, in order to run Python code and get Python IntelliSense, you must tell VS Code which interpreter to use.

From within VS Code, select a Python 3 interpreter by opening the Command Palette (kb(workbench.action.showCommands)), start typing the Python: Select Interpreter command to search, then select the command. You can also use the Select Python Environment option on the Status Bar if available (it may already show a selected interpreter, too):

No interpreter selected

The command presents a list of available interpreters that VS Code can find automatically, including virtual environments. If you don’t see the desired interpreter, see Configuring Python environments.

Select an Interpreter

Note: When using an Anaconda distribution, the correct interpreter should have the suffix ('base':conda), for example Python 3.7.3 64-bit ('base':conda).

Selecting an interpreter sets which interpreter will be used by the Python extension for that workspace.

Note: If you select an interpreter without a workspace folder open, VS Code sets python.defaultInterpreterPath in User scope instead, which sets the default interpreter for VS Code in general. The user setting makes sure you always have a default interpreter for Python projects. The workspace settings lets you override the user setting.

Create a Python Hello World source code file

From the File Explorer toolbar, select the New File button on the hello folder:

File Explorer New File

Name the file hello.py, and it automatically opens in the editor:

File Explorer hello.py

By using the .py file extension, you tell VS Code to interpret this file as a Python program, so that it evaluates the contents with the Python extension and the selected interpreter.

Note: The File Explorer toolbar also allows you to create folders within your workspace to better organize your code. You can use the New folder button to quickly create a folder.

Now that you have a code file in your Workspace, enter the following source code in hello.py:

msg = "Hello World"
print(msg)

When you start typing print, notice how IntelliSense presents auto-completion options.

IntelliSense appearing for Python code

IntelliSense and auto-completions work for standard Python modules as well as other packages you’ve installed into the environment of the selected Python interpreter. It also provides completions for methods available on object types. For example, because the msg variable contains a string, IntelliSense provides string methods when you type msg.:

IntelliSense appearing for a variable whose type provides methods

Feel free to experiment with IntelliSense some more, but then revert your changes so you have only the msg variable and the print call, and save the file (kb(workbench.action.files.save)).

For full details on editing, formatting, and refactoring, see Editing code. The Python extension also has full support for Linting.

Run Hello World

It’s simple to run hello.py with Python. Just click the Run Python File in Terminal play button in the top-right side of the editor.

Using the run python file in terminal button

The button opens a terminal panel in which your Python interpreter is automatically activated, then runs python3 hello.py (macOS/Linux) or python hello.py (Windows):

Program output in a Python terminal

There are three other ways you can run Python code within VS Code:

  • Right-click anywhere in the editor window and select Run Python File in Terminal (which saves the file automatically):

    Run Python File in Terminal command in the Python editor

  • Select one or more lines, then press kbstyle(Shift+Enter) or right-click and select Run Selection/Line in Python Terminal. This command is convenient for testing just a part of a file.

  • From the Command Palette (kb(workbench.action.showCommands)), select the Python: Start REPL command to open a REPL terminal for the currently selected Python interpreter. In the REPL, you can then enter and run lines of code one at a time.

Configure and run the debugger

Let’s now try debugging our simple Hello World program.

First, set a breakpoint on line 2 of hello.py by placing the cursor on the print call and pressing kb(editor.debug.action.toggleBreakpoint). Alternately, just click in the editor’s left gutter, next to the line numbers. When you set a breakpoint, a red circle appears in the gutter.

Setting a breakpoint in hello.py

Next, to initialize the debugger, press kb(workbench.action.debug.start). Since this is your first time debugging this file, a configuration menu will open from the Command Palette allowing you to select the type of debug configuration you would like for the opened file.

Debug configurations after launch.json is created

Note: VS Code uses JSON files for all of its various configurations; launch.json is the standard name for a file containing debugging configurations.

These different configurations are fully explained in Debugging configurations; for now, just select Python File, which is the configuration that runs the current file shown in the editor using the currently selected Python interpreter.

You can also start the debugger by clicking on the down-arrow next to the run button on the editor, and selecting Debug Python File in Terminal.

Using the debug Python file in terminal button

The debugger will stop at the first line of the file breakpoint. The current line is indicated with a yellow arrow in the left margin. If you examine the Local variables window at this point, you will see now defined msg variable appears in the Local pane.

Debugging step 2 - variable defined

A debug toolbar appears along the top with the following commands from left to right: continue (kb(workbench.action.debug.start)), step over (kb(workbench.action.debug.stepOver)), step into (kb(workbench.action.debug.stepInto)), step out (kb(workbench.action.debug.stepOut)), restart (kb(workbench.action.debug.restart)), and stop (kb(workbench.action.debug.stop)).

Debugging toolbar

The Status Bar also changes color (orange in many themes) to indicate that you’re in debug mode. The Python Debug Console also appears automatically in the lower right panel to show the commands being run, along with the program output.

To continue running the program, select the continue command on the debug toolbar (kb(workbench.action.debug.start)). The debugger runs the program to the end.

Tip Debugging information can also be seen by hovering over code, such as variables. In the case of msg, hovering over the variable will display the string Hello world in a box above the variable.

You can also work with variables in the Debug Console (If you don’t see it, select Debug Console in the lower right area of VS Code, or select it from the menu.) Then try entering the following lines, one by one, at the > prompt at the bottom of the console:

msg
msg.capitalize()
msg.split()

Debugging step 3 - using the debug console

Select the blue Continue button on the toolbar again (or press F5) to run the program to completion. «Hello World» appears in the Python Debug Console if you switch back to it, and VS Code exits debugging mode once the program is complete.

If you restart the debugger, the debugger again stops on the first breakpoint.

To stop running a program before it’s complete, use the red square stop button on the debug toolbar (kb(workbench.action.debug.stop)), or use the Run > Stop debugging menu command.

For full details, see Debugging configurations, which includes notes on how to use a specific Python interpreter for debugging.

Tip: Use Logpoints instead of print statements: Developers often litter source code with print statements to quickly inspect variables without necessarily stepping through each line of code in a debugger. In VS Code, you can instead use Logpoints. A Logpoint is like a breakpoint except that it logs a message to the console and doesn’t stop the program. For more information, see Logpoints in the main VS Code debugging article.

Install and use packages

Let’s now run an example that’s a little more interesting. In Python, packages are how you obtain any number of useful code libraries, typically from PyPI. For this example, you use the matplotlib and numpy packages to create a graphical plot as is commonly done with data science. (Note that matplotlib cannot show graphs when running in the Windows Subsystem for Linux as it lacks the necessary UI support.)

Return to the Explorer view (the top-most icon on the left side, which shows files), create a new file called standardplot.py, and paste in the following source code:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 20, 100)  # Create a list of evenly-spaced numbers over the range
plt.plot(x, np.sin(x))       # Plot the sine of each x point
plt.show()                   # Display the plot

Tip: If you enter the above code by hand, you may find that auto-completions change the names after the as keywords when you press kbstyle(Enter) at the end of a line. To avoid this, type a space, then kbstyle(Enter).

Next, try running the file in the debugger using the «Python: Current file» configuration as described in the last section.

Unless you’re using an Anaconda distribution or have previously installed the matplotlib package, you should see the message, «ModuleNotFoundError: No module named ‘matplotlib'». Such a message indicates that the required package isn’t available in your system.

To install the matplotlib package (which also installs numpy as a dependency), stop the debugger and use the Command Palette to run Terminal: Create New Terminal (kb(workbench.action.terminal.new)). This command opens a command prompt for your selected interpreter.

A best practice among Python developers is to avoid installing packages into a global interpreter environment. You instead use a project-specific virtual environment that contains a copy of a global interpreter. Once you activate that environment, any packages you then install are isolated from other environments. Such isolation reduces many complications that can arise from conflicting package versions. To create a virtual environment and install the required packages, enter the following commands as appropriate for your operating system:

Note: For additional information about virtual environments, see Environments.
v

  1. Create a virtual environment using the Create Environment command

    From within VS Code, you can create non-global environments, using Venv or Anaconda, by opening the Command Palette (kb(workbench.action.showCommands)), start typing the Python: Create Environment command to search, and then select the command. You can also trigger the Python: Create Environment command through the Getting Started with Python page.

    The command presents a list of environment types, Venv or Conda. For this example, select Venv.

    Create Environment dropdown

    The command then presents a list of interpreters that can be used for your project.

    Virtual environment interpreter selection

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

    Create environment status notification

    The command will also install necessary packages outlined in a requirements/dependencies file, such as requirements.txt, pyproject.toml, or environment.yml, located in the project folder.

    Note: If you want to create an environment manually, or run into error in the environment creation process, visit the Environments page.

  2. Ensure your new environment is selected by using the Python: Select Interpreter command from the Command Palette.

    Select an Interpreter

  3. Install the packages

    # Don't use with Anaconda distributions because they include matplotlib already.
    
    # macOS
    python3 -m pip install matplotlib
    
    # Windows (may require elevation)
    python -m pip install matplotlib
    
    # Linux (Debian)
    apt-get install python3-tk
    python3 -m pip install matplotlib
  4. Rerun the program now (with or without the debugger) and after a few moments a plot window appears with the output:

    matplotlib output

  5. Once you are finished, type deactivate in the terminal window to deactivate the virtual environment.

For additional examples of creating and activating a virtual environment and installing packages, see the Django tutorial and the Flask tutorial.

Next steps

You can configure VS Code to use any Python environment you have installed, including virtual and conda environments. You can also use a separate environment for debugging. For full details, see Environments.

To learn more about the Python language, follow any of the programming tutorials listed on python.org within the context of VS Code.

To learn to build web apps with the Django and Flask frameworks, see the following tutorials:

  • Use Django in Visual Studio Code
  • Use Flask in Visual Studio Code

There is then much more to explore with Python in Visual Studio Code:

  • Editing code — Learn about autocomplete, IntelliSense, formatting, and refactoring for Python.
  • Linting — Enable, configure, and apply a variety of Python linters.
  • 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.
  • Deploy Python to Azure App Service
  • Deploy Python to Container Apps

Содержание:развернуть

  • Установка VSCode
  • Windows

  • Linux

  • macOS

  • Настройка под Python
  • Установка расширения «Python»

  • Выбор версии интерпретатора Python

  • Работа в VS Code
  • Запуск редактора

  • Интерфейс

  • Запуск Python-кода (run)

  • Отладка (debugger)

  • Тестирование (testing)

  • GIT

  • ТОП плагинов для VS Code

В 2016-м году компания Microsoft представила миру свой новый редактор программного кода. В отличие от старшей сестры — полноценной IDE Visual Studio — VS Code получился куда более компактным и легковесным решением. Он разработан как кроссплатформенное ПО и может быть успешно установлен в системах Windows, Linux и macOS.

Visual Studio Code

Бесплатность Visual Studio Code абсолютно не мешает ему обладать весьма богатым современным функционалом. VS Code имеет встроенный отладчик, позволяет работать с системами контроля версий, обеспечивает интеллектуальную подсветку синтаксиса, а также поддерживает целый ряд популярных языков программирования.

И хоть, за годы своего существования, VSCode зарекомендовал себя, в основном, как продукт для веб-разработки, в 2018 году появилось расширение «Python«, которое дало программистам многочисленные возможности для редактирования, отладки и тестирования кода на нашем любимом языке.

Установка VSCode

Поистине смешные системные требования Visual Studio Code обязательно порадуют владельцев старых машин.

Для полноценной работы редактору требуется всего лишь 1 ГБ оперативной памяти и процессор с частотой от 1.6 ГГц.

Такое сочетание лёгкости и функциональности действительно подкупает, а отсутствие в VS Code каких-либо «лагов» и «фризов» делают разработку ещё более приятным и увлекательным занятием.

Установка редактора никуда не отходит от данной парадигмы и тоже является весьма простым и понятным процессом.

Windows

Сначала нужно скачать с официального сайта установочный файл небольшого размера, а затем установить сам ВиЭс код, следуя подсказкам от мастера установки.

VS Code можно скачать с официального сайта code.visualstudio.com

Linux

На сайте программы можно изучить способы инсталляции редактора на разные Linux-дистрибутивы, но здесь рассмотрим процесс установки для самого популярного из них — Ubuntu.

Установить VSCode можно несколькими способами:

Способ №1: Самый простой способ — воспользоваться менеджером установки «Ubuntu Software».

Откройте «Ubuntu Software» -> введите в поиск «VSCode» -> выберите первую строку и нажмите «Install»

Способ №2: Скачать дистрибутив с официального сайта и установить его командой:

sudo apt install ./<file>.deb

О других способах установки читайте на странице официальной документации в разделе «Setup«;

macOS

Алгоритм установки редактора внутри яблочной операционной системы также не представляет собой ничего сложного:

  1. Сначала нужно скачать Visual Studio Code с официального сайта.
  2. Затем открыть список загрузок браузера и найти там VSCode-Darwin-Stable.zip.
  3. Нажмите на иконку увеличительного стекла, чтобы открыть архив.
  4. Перетащите Visual Studio Code.app в папку приложений, сделав ее доступной на панели запуска.
  5. Щёлкните правой кнопкой мыши по значку и выберите команду «Оставить в Dock«.

Настройка под Python

Установка расширения «Python»

Для начала работы с Python, нужно перейти на вкладку Extensions, что находится на панели слева, либо нажать Ctrl + Shift + X. Сделав это, набираем в строке поиска «Python«.

Для начала работы с Python, установите расширение от Microsoft — «Python».

VS Code поддерживает, как вторую, так и третью версию языка, однако python интерпретатор на свою машину вам придётся поставить самостоятельно.

Подробнее о том, как установить Python:

Если вы новичок и только начинаете работу с Python или же не имеете каких-то особых указаний на этот счёт, то лучшим выбором станет именно актуальная третья версия.

Вот краткий список основных возможностей расширения «Python»:

  • Автодополнение кода.
  • Отладка.
  • Поддержка сниппетов.
  • Написание и проведение тестов.
  • Использование менеджера пакетов Conda.
  • Возможность создания виртуальных сред.
  • Поддержка интерактивных вычисления на Jupyter Notebooks.

Выбор версии интерпретатора Python

После от вас потребуется совершить выбор версии интерпретатора внутри самого редактора (обычно VS code знает, где он расположен). Для этого:

  1. Откройте командную строку VSCode (Command Palette) комбинацией Ctrl + Shift + P.
  2. Начинайте печатать «Python: Select Interpreter«;
  3. После, выберите нужную версию интерпретатора.

Выбор интерпретатора в VSCode

Также выбрать версию можно в панели активности в левом нижнем углу:

Выбор версии Python-интерпретатора в панели активности VS Code

Если вы хотите использовать pipenv в своем проекте:

  1. Установите pipenv командой pip install pipenv (или pip3 install pipenv);
  2. Выполните команду pipenv install;
  3. Откройте «Command Palette«, напечатайте «Python: Select Interpreter» и из списка выберите нужную версию интерпретатор.

Подробнее о pipenv:

Работа в VS Code

Запуск редактора

Как и другие современные редакторы и среды разработки, VS Code фиксирует состояние на момент закрытия программы. При следующем запуске, он открывается в том же самом виде, в котором существовал до завершения работы.

Так как VSCode, в первую очередь — редактор, а не полновесная среда разработки, здесь нет особой привязки к проекту. Вы можете сходу создавать, открывать и редактировать нужные вам файлы. Достаточно, после запуска, нажать Open File или New File и можно начинать работу.

Интерфейс

Интерфейс программы разрабатывался в стремлении сделать его как можно более простым и интуитивно понятным. Дизайнеры постарались, как максимизировать пространство для редактора, так и оставить достаточно места для отображения проводника по вашему проекту.

Так выглядит интерфейс VS Code

Весь UI VSCode разделился, таким образом, на шесть областей:

  1. Область редактора — основная область для написания и редактирования вашего кода.
  2. Боковая панель — здесь содержатся различные представления (например проводник).
  3. Строка состояния — визуализирует рабочую информацию об открытом в данный момент файле.
  4. Командная панель — классическая главная панель с вкладками file, edit, go, run и так далее.
  5. Панель активности — область в крайнем левом углу, где находятся важные вспомогательные вкладки, вроде контроля версий, дебаггера и магазина расширений.
  6. Мультипанель — панель на которой располагается вывод отладку, информация об ошибках и предупреждениях, а также встроенный в VS Code терминал.

Запуск Python-кода (run)

Выполнить код можно несколькими способами. Самый простой — комбинацией Ctrl + Alt + N.

Для запуска python-кода выполните комбинацию «Ctrl + Alt + N»

Также можно вызвать скрипт контекстным меню, выбрав строку «Run Python File in Terminal«.

Запуск Python-кода через контекстное меню в VSCode

Или нажав иконку «Run» в правом верхнем углу.

Иконка «Run» в правом верхнем углу запустит Python-код на выполнение

Отладка (debugger)

Возможность полноценной отладки — сильная сторона редактора. Чтобы перейти в режим отладки, нужно установить точку останова и нажать F5.

Для перехода в режим отладки, установите breakpoint и нажмите «F5»

Вся информация о текущем состоянии будет выводиться на панель дебаггера.

Так выглядит debugger в VSCode

Слева откроется панель дебаггера с информацией о состоянии переменных (Variables), отслеживаемых переменных (Watch) и стеке вызова (Call stack).

Сверху расположена панель инструментов дебаггера.

Панель инструментов дебаггера в VSCode

Рассмотрим команды (слева направо):

  1. continue (F5) — перемещает между breakpoint-ами;
  2. step over (F10) — построчное (пошаговое) перемещение;
  3. step into (F11) — построчное (пошаговое) перемещение c заходом в каждую вызываемую функцию;
  4. step out (Shift + F11) — работает противоположно step into — выходит из вызванной функции, если в данный момент вы находитесь внутри неё. Далее работает как continue.
  5. restart (Ctrl + Shift + F5) — начинаем отладку с начала.
  6. stop (Shift + F5) — остановка и выход из режима отладки.

Чаще всего для отладки используются continue (F5) и step over (F10).

С отладкой разобрались 👌.

Тестирование (testing)

С поддержкой тестов у VS Code тоже всё в порядке, однако, по умолчанию тестирование отключено. Для его активации нужна небольшая настройка.

Сначала следует нажать комбинацию клавиш Ctrl + Shift + P и в так называемой палитре команд выбрать Python: Configure Tests.

Для выбора фреймворка для тестов, выполните комбинацию «Ctrl + Shift + P» и наберите «Python: Configure Tests»

Редактор предложит вам определить фреймворк (мы выбрали «pytest») и папку, содержащую тесты (мы выбрали «. Root directory»).

Создадим новый файл с тестами (test_app.py) и запустим его, кликнув правой кнопкой мыши на этом файле и выбрав пункт «Run Current Test File«.

Также тесты можно запускать по нажатию на кнопку Run Tests в нижней строке состояния

Запуск тестов в VSCode с использованием фреймворка pytest.

Чтобы увидеть результаты, необходимо открыть вкладку Output на панели, и в выпадающем меню выбрать пункт PythonTestLog.

Результат Python-тестов в Output

Как мы видим, первый тест прошел успешно, а второй провалился.

Для удобства работы с тестами, установим расширение «Python Test Explorer for Visual Studio Code«.

Расширение для VSCode «Python Test Explorer for Visual Studio Code»

Теперь информацию по тестам можно посмотрев, кликнув на левой панели «иконку с колбой«, предварительно запустив тесты.

Вкладка «test» (иконка с колбой в панели слева) откроет удобный проводник для запуска тестов и просмотра их состояния.

GIT

Для начала работы с системами контроля версий обратимся к вкладке Source Control, что находится на панели активности слева (или Ctrl + Shift + G).

По умолчанию VS Code дружит с Git и GitHub

Поддержку других систем возможно настроить самостоятельно, установив соответствующие расширения.

Чтобы связать проект с github (или gitlab), сперва необходимо скачать на ваш ПК git (если ещё не скачан). VSCode автоматически определит его местоположение, и затем у вас появится возможность синхронизации.

Для работы с git, зайдите в меню слева «Source Control»

Все основные и необходимые операции для контроля версий будут находиться прямиком внутри редактора: коммитить, пуллить, пушить, создавать бранчи и просматривать изменения вы можете, не выходя из VisualStudioCode.

Все необходимые команды для работы в git находятся в меню панели «Source Control» (3 точки)

А для удобного просмотра изменений в git, советую установить расширение «Git Graph«. После его установки, на панели «Source Control» появится новая кнопка, которая отобразит граф состояния (git log).

Git Graph — VS Code расширение для удобного просмотра графа состояния (git log)

ТОП плагинов для VS Code

  • Python extension for Visual Studio Code — официальное расширение Python от Microsoft.
  • TabNine — магией машинного обучения пропитан сей плагин сотворённый для высших целей интеллектуального автозаполнения кода.
  • Python Preview — расширение, способствующее более простой и лёгкой отладке в VSCode.
  • Indent-Rainbow — плагин выделяет цветом все отступы, чередуя четыре разных цвета на каждом блоке.
  • Bracket Pair Colorizer — плагин для лучшей читаемости кода, который разукрашивает соответствующие друг другу скобки в один цвет.
  • Better Comments — позволяет создавать более красивые и удобные комментарии к вашему программному коду.
  • Python Test Explorer for Visual Studio Code — запуск тестов с помощью TestExplorer UI.
  • Debugger for Chrome — добавление отладчика браузера Google Chrome в ваш редактор.
  • Path Intellisense — плагин, который автозаполняет имена файлов.
  • Python Docstring Generator — плагин для быстрого генерирования docstrings.
  • Bookmarks — расширение позволяет создавать закладки в коде и перемещаться по ним с помощью горячих клавиш.
  • Error Lens — удобная подсветка ошибок.
  • TODO Highlight — подсветка TODO и FIXME в комментариях.

Getting Started with Python in VS Code

In this tutorial, you will use Python 3 to create the simplest Python «Hello World» application in Visual Studio Code. By using the Python extension, you make VS Code into a great lightweight Python IDE (which you may find a productive alternative to PyCharm).

This tutorial introduces you to VS Code as a Python environment — primarily how to edit, run, and debug code through the following tasks:

  • Write, run, and debug a Python «Hello World» Application
  • Learn how to install packages by creating Python virtual environments
  • Write a simple Python script to plot figures within VS Code

This tutorial is not intended to teach you Python itself. Once you are familiar with the basics of VS Code, you can then follow any of the programming tutorials on python.org within the context of VS Code for an introduction to the language.

If you have any problems, you can search for answers or ask a question on the Python extension Discussions Q&A.

Prerequisites

To successfully complete this tutorial, you need to first setup your Python development environment. Specifically, this tutorial requires:

  • Python 3
  • VS Code application
  • VS Code Python extension

Install Visual Studio Code and the Python Extension

  1. If you have not already done so, install VS Code.

  2. Next, install the Python extension for VS Code from the Visual Studio Marketplace. For additional details on installing extensions, see Extension Marketplace. The Python extension is named Python and it’s published by Microsoft.

    Python extension on Marketplace

Install a Python interpreter

Along with the Python extension, you need to install a Python interpreter. Which interpreter you use is dependent on your specific needs, but some guidance is provided below.

Windows

Install Python from python.org. You can typically use the Download Python button that appears first on the page to download the latest version.

Note: If you don’t have admin access, an additional option for installing Python on Windows is to use the Microsoft Store. The Microsoft Store provides installs of supported Python versions.

For additional information about using Python on Windows, see Using Python on Windows at Python.org

macOS

The system install of Python on macOS is not supported. Instead, a package management system like Homebrew is recommended. To install Python using Homebrew on macOS use brew install python3 at the Terminal prompt.

Note On macOS, make sure the location of your VS Code installation is included in your PATH environment variable. See these setup instructions for more information.

Linux

The built-in Python 3 installation on Linux works well, but to install other Python packages you must install pip with get-pip.py.

Other options

  • Data Science: If your primary purpose for using Python is Data Science, then you might consider a download from Anaconda. Anaconda provides not just a Python interpreter, but many useful libraries and tools for data science.

  • Windows Subsystem for Linux: If you are working on Windows and want a Linux environment for working with Python, the Windows Subsystem for Linux (WSL) is an option for you. If you choose this option, you’ll also want to install the WSL extension. For more information about using WSL with VS Code, see VS Code Remote Development or try the Working in WSL tutorial, which will walk you through setting up WSL, installing Python, and creating a Hello World application running in WSL.

Verify the Python installation

To verify that you’ve installed Python successfully on your machine, run one of the following commands (depending on your operating system):

  • Linux/macOS: open a Terminal Window and type the following command:

    python3 --version
    
  • Windows: open a command prompt and run the following command:

    py -3 --version
    

If the installation was successful, the output window should show the version of Python that you installed.

Note You can use the py -0 command in the VS Code integrated terminal to view the versions of python installed on your machine. The default interpreter is identified by an asterisk (*).

Start VS Code in a workspace folder

By starting VS Code in a folder, that folder becomes your «workspace». VS Code stores settings that are specific to that workspace in .vscode/settings.json, which are separate from user settings that are stored globally.

Using a command prompt or terminal, create an empty folder called «hello», navigate into it, and open VS Code (code) in that folder (.) by entering the following commands:

mkdir hello
cd hello
code .

Note: If you’re using an Anaconda distribution, be sure to use an Anaconda command prompt.

Alternately, you can run VS Code through the operating system UI, then use File > Open Folder to open the project folder.

Select a Python interpreter

Python is an interpreted language. Thus, in order to run Python code and get Python IntelliSense, you must tell VS Code which interpreter to use.

From within VS Code, select a Python 3 interpreter by opening the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)), start typing the Python: Select Interpreter command to search, then select the command. You can also use the Select Python Environment option on the Status Bar if available (it may already show a selected interpreter, too):

No interpreter selected

The command presents a list of available interpreters that VS Code can find automatically, including virtual environments. If you don’t see the desired interpreter, see Configuring Python environments.

Select an Interpreter

Note: When using an Anaconda distribution, the correct interpreter should have the suffix ('base':conda), for example Python 3.7.3 64-bit ('base':conda).

Selecting an interpreter sets which interpreter will be used by the Python extension for that workspace.

Note: If you select an interpreter without a workspace folder open, VS Code sets python.defaultInterpreterPath in User scope instead, which sets the default interpreter for VS Code in general. The user setting makes sure you always have a default interpreter for Python projects. The workspace settings lets you override the user setting.

Create a Python Hello World source code file

From the File Explorer toolbar, select the New File button on the hello folder:

File Explorer New File

Name the file hello.py, and it automatically opens in the editor:

File Explorer hello.py

By using the .py file extension, you tell VS Code to interpret this file as a Python program, so that it evaluates the contents with the Python extension and the selected interpreter.

Note: The File Explorer toolbar also allows you to create folders within your workspace to better organize your code. You can use the New folder button to quickly create a folder.

Now that you have a code file in your Workspace, enter the following source code in hello.py:

msg = "Hello World"
print(msg)

When you start typing print, notice how IntelliSense presents auto-completion options.

IntelliSense appearing for Python code

IntelliSense and auto-completions work for standard Python modules as well as other packages you’ve installed into the environment of the selected Python interpreter. It also provides completions for methods available on object types. For example, because the msg variable contains a string, IntelliSense provides string methods when you type msg.:

IntelliSense appearing for a variable whose type provides methods

Feel free to experiment with IntelliSense some more, but then revert your changes so you have only the msg variable and the print call, and save the file (⌘S (Windows, Linux Ctrl+S)).

For full details on editing, formatting, and refactoring, see Editing code. The Python extension also has full support for Linting.

Run Hello World

It’s simple to run hello.py with Python. Just click the Run Python File in Terminal play button in the top-right side of the editor.

Using the run python file in terminal button

The button opens a terminal panel in which your Python interpreter is automatically activated, then runs python3 hello.py (macOS/Linux) or python hello.py (Windows):

Program output in a Python terminal

There are three other ways you can run Python code within VS Code:

  • Right-click anywhere in the editor window and select Run Python File in Terminal (which saves the file automatically):

    Run Python File in Terminal command in the Python editor

  • Select one or more lines, then press Shift+Enter or right-click and select Run Selection/Line in Python Terminal. This command is convenient for testing just a part of a file.

  • From the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)), select the Python: Start REPL command to open a REPL terminal for the currently selected Python interpreter. In the REPL, you can then enter and run lines of code one at a time.

Configure and run the debugger

Let’s now try debugging our simple Hello World program.

First, set a breakpoint on line 2 of hello.py by placing the cursor on the print call and pressing F9. Alternately, just click in the editor’s left gutter, next to the line numbers. When you set a breakpoint, a red circle appears in the gutter.

Setting a breakpoint in hello.py

Next, to initialize the debugger, press F5. Since this is your first time debugging this file, a configuration menu will open from the Command Palette allowing you to select the type of debug configuration you would like for the opened file.

Debug configurations after launch.json is created

Note: VS Code uses JSON files for all of its various configurations; launch.json is the standard name for a file containing debugging configurations.

These different configurations are fully explained in Debugging configurations; for now, just select Python File, which is the configuration that runs the current file shown in the editor using the currently selected Python interpreter.

You can also start the debugger by clicking on the down-arrow next to the run button on the editor, and selecting Debug Python File in Terminal.

Using the debug Python file in terminal button

The debugger will stop at the first line of the file breakpoint. The current line is indicated with a yellow arrow in the left margin. If you examine the Local variables window at this point, you will see now defined msg variable appears in the Local pane.

Debugging step 2 - variable defined

A debug toolbar appears along the top with the following commands from left to right: continue (F5), step over (F10), step into (F11), step out (⇧F11 (Windows, Linux Shift+F11)), restart (⇧⌘F5 (Windows, Linux Ctrl+Shift+F5)), and stop (⇧F5 (Windows, Linux Shift+F5)).

Debugging toolbar

The Status Bar also changes color (orange in many themes) to indicate that you’re in debug mode. The Python Debug Console also appears automatically in the lower right panel to show the commands being run, along with the program output.

To continue running the program, select the continue command on the debug toolbar (F5). The debugger runs the program to the end.

Tip Debugging information can also be seen by hovering over code, such as variables. In the case of msg, hovering over the variable will display the string Hello world in a box above the variable.

You can also work with variables in the Debug Console (If you don’t see it, select Debug Console in the lower right area of VS Code, or select it from the menu.) Then try entering the following lines, one by one, at the > prompt at the bottom of the console:

msg
msg.capitalize()
msg.split()

Debugging step 3 - using the debug console

Select the blue Continue button on the toolbar again (or press F5) to run the program to completion. «Hello World» appears in the Python Debug Console if you switch back to it, and VS Code exits debugging mode once the program is complete.

If you restart the debugger, the debugger again stops on the first breakpoint.

To stop running a program before it’s complete, use the red square stop button on the debug toolbar (⇧F5 (Windows, Linux Shift+F5)), or use the Run > Stop debugging menu command.

For full details, see Debugging configurations, which includes notes on how to use a specific Python interpreter for debugging.

Tip: Use Logpoints instead of print statements: Developers often litter source code with print statements to quickly inspect variables without necessarily stepping through each line of code in a debugger. In VS Code, you can instead use Logpoints. A Logpoint is like a breakpoint except that it logs a message to the console and doesn’t stop the program. For more information, see Logpoints in the main VS Code debugging article.

Install and use packages

Let’s now run an example that’s a little more interesting. In Python, packages are how you obtain any number of useful code libraries, typically from PyPI. For this example, you use the matplotlib and numpy packages to create a graphical plot as is commonly done with data science. (Note that matplotlib cannot show graphs when running in the Windows Subsystem for Linux as it lacks the necessary UI support.)

Return to the Explorer view (the top-most icon on the left side, which shows files), create a new file called standardplot.py, and paste in the following source code:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 20, 100)  # Create a list of evenly-spaced numbers over the range
plt.plot(x, np.sin(x))       # Plot the sine of each x point
plt.show()                   # Display the plot

Tip: If you enter the above code by hand, you may find that auto-completions change the names after the as keywords when you press Enter at the end of a line. To avoid this, type a space, then Enter.

Next, try running the file in the debugger using the «Python: Current file» configuration as described in the last section.

Unless you’re using an Anaconda distribution or have previously installed the matplotlib package, you should see the message, «ModuleNotFoundError: No module named ‘matplotlib'». Such a message indicates that the required package isn’t available in your system.

To install the matplotlib package (which also installs numpy as a dependency), stop the debugger and use the Command Palette to run Terminal: Create New Terminal (⌃⇧` (Windows, Linux Ctrl+Shift+`)). This command opens a command prompt for your selected interpreter.

A best practice among Python developers is to avoid installing packages into a global interpreter environment. You instead use a project-specific virtual environment that contains a copy of a global interpreter. Once you activate that environment, any packages you then install are isolated from other environments. Such isolation reduces many complications that can arise from conflicting package versions. To create a virtual environment and install the required packages, enter the following commands as appropriate for your operating system:

Note: For additional information about virtual environments, see Environments.
v

  1. Create a virtual environment using the Create Environment command

    From within VS Code, you can create non-global environments, using Venv or Anaconda, by opening the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)), start typing the Python: Create Environment command to search, and then select the command. You can also trigger the Python: Create Environment command through the Getting Started with Python page.

    The command presents a list of environment types, Venv or Conda. For this example, select Venv.

    Create Environment dropdown

    The command then presents a list of interpreters that can be used for your project.

    Virtual environment interpreter selection

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

    Create environment status notification

    The command will also install necessary packages outlined in a requirements/dependencies file, such as requirements.txt, pyproject.toml, or environment.yml, located in the project folder.

    Note: If you want to create an environment manually, or run into error in the environment creation process, visit the Environments page.

  2. Ensure your new environment is selected by using the Python: Select Interpreter command from the Command Palette.

    Select an Interpreter

  3. Install the packages

    # Don't use with Anaconda distributions because they include matplotlib already.
    
    # macOS
    python3 -m pip install matplotlib
    
    # Windows (may require elevation)
    python -m pip install matplotlib
    
    # Linux (Debian)
    apt-get install python3-tk
    python3 -m pip install matplotlib
    
  4. Rerun the program now (with or without the debugger) and after a few moments a plot window appears with the output:

    matplotlib output

  5. Once you are finished, type deactivate in the terminal window to deactivate the virtual environment.

For additional examples of creating and activating a virtual environment and installing packages, see the Django tutorial and the Flask tutorial.

Next steps

You can configure VS Code to use any Python environment you have installed, including virtual and conda environments. You can also use a separate environment for debugging. For full details, see Environments.

To learn more about the Python language, follow any of the programming tutorials listed on python.org within the context of VS Code.

To learn to build web apps with the Django and Flask frameworks, see the following tutorials:

  • Use Django in Visual Studio Code
  • Use Flask in Visual Studio Code

There is then much more to explore with Python in Visual Studio Code:

  • Editing code — Learn about autocomplete, IntelliSense, formatting, and refactoring for Python.
  • Linting — Enable, configure, and apply a variety of Python linters.
  • 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.
  • Deploy Python to Azure App Service
  • Deploy Python to Container Apps

1/20/2023

Getting Started with Python in VS Code

In this tutorial, you will use Python 3 to create the simplest Python «Hello World» application in Visual Studio Code. By using the Python extension, you make VS Code into a great lightweight Python IDE (which you may find a productive alternative to PyCharm).

This tutorial introduces you to VS Code as a Python environment — primarily how to edit, run, and debug code through the following tasks:

  • Write, run, and debug a Python «Hello World» Application
  • Learn how to install packages by creating Python virtual environments
  • Write a simple Python script to plot figures within VS Code

This tutorial is not intended to teach you Python itself. Once you are familiar with the basics of VS Code, you can then follow any of the programming tutorials on python.org within the context of VS Code for an introduction to the language.

If you have any problems, you can search for answers or ask a question on the Python extension Discussions Q&A.

Prerequisites

To successfully complete this tutorial, you need to first setup your Python development environment. Specifically, this tutorial requires:

  • Python 3
  • VS Code application
  • VS Code Python extension

Install Visual Studio Code and the Python Extension

  1. If you have not already done so, install VS Code.

  2. Next, install the Python extension for VS Code from the Visual Studio Marketplace. For additional details on installing extensions, see Extension Marketplace. The Python extension is named Python and it’s published by Microsoft.

    Python extension on Marketplace

Install a Python interpreter

Along with the Python extension, you need to install a Python interpreter. Which interpreter you use is dependent on your specific needs, but some guidance is provided below.

Windows

Install Python from python.org. You can typically use the Download Python button that appears first on the page to download the latest version.

Note: If you don’t have admin access, an additional option for installing Python on Windows is to use the Microsoft Store. The Microsoft Store provides installs of supported Python versions.

For additional information about using Python on Windows, see Using Python on Windows at Python.org

macOS

The system install of Python on macOS is not supported. Instead, a package management system like Homebrew is recommended. To install Python using Homebrew on macOS use brew install python3 at the Terminal prompt.

Note On macOS, make sure the location of your VS Code installation is included in your PATH environment variable. See these setup instructions for more information.

Linux

The built-in Python 3 installation on Linux works well, but to install other Python packages you must install pip with get-pip.py.

Other options

  • Data Science: If your primary purpose for using Python is Data Science, then you might consider a download from Anaconda. Anaconda provides not just a Python interpreter, but many useful libraries and tools for data science.

  • Windows Subsystem for Linux: If you are working on Windows and want a Linux environment for working with Python, the Windows Subsystem for Linux (WSL) is an option for you. If you choose this option, you’ll also want to install the WSL extension. For more information about using WSL with VS Code, see VS Code Remote Development or try the Working in WSL tutorial, which will walk you through setting up WSL, installing Python, and creating a Hello World application running in WSL.

Verify the Python installation

To verify that you’ve installed Python successfully on your machine, run one of the following commands (depending on your operating system):

  • Linux/macOS: open a Terminal Window and type the following command:

    python3 --version
    
  • Windows: open a command prompt and run the following command:

    py -3 --version
    

If the installation was successful, the output window should show the version of Python that you installed.

Note You can use the py -0 command in the VS Code integrated terminal to view the versions of python installed on your machine. The default interpreter is identified by an asterisk (*).

Start VS Code in a workspace folder

By starting VS Code in a folder, that folder becomes your «workspace». VS Code stores settings that are specific to that workspace in .vscode/settings.json, which are separate from user settings that are stored globally.

Using a command prompt or terminal, create an empty folder called «hello», navigate into it, and open VS Code (code) in that folder (.) by entering the following commands:

mkdir hello
cd hello
code .

Note: If you’re using an Anaconda distribution, be sure to use an Anaconda command prompt.

Alternately, you can run VS Code through the operating system UI, then use File > Open Folder to open the project folder.

Select a Python interpreter

Python is an interpreted language. Thus, in order to run Python code and get Python IntelliSense, you must tell VS Code which interpreter to use.

From within VS Code, select a Python 3 interpreter by opening the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)), start typing the Python: Select Interpreter command to search, then select the command. You can also use the Select Python Environment option on the Status Bar if available (it may already show a selected interpreter, too):

No interpreter selected

The command presents a list of available interpreters that VS Code can find automatically, including virtual environments. If you don’t see the desired interpreter, see Configuring Python environments.

Select an Interpreter

Note: When using an Anaconda distribution, the correct interpreter should have the suffix ('base':conda), for example Python 3.7.3 64-bit ('base':conda).

Selecting an interpreter sets which interpreter will be used by the Python extension for that workspace.

Note: If you select an interpreter without a workspace folder open, VS Code sets python.defaultInterpreterPath in User scope instead, which sets the default interpreter for VS Code in general. The user setting makes sure you always have a default interpreter for Python projects. The workspace settings lets you override the user setting.

Create a Python Hello World source code file

From the File Explorer toolbar, select the New File button on the hello folder:

File Explorer New File

Name the file hello.py, and it automatically opens in the editor:

File Explorer hello.py

By using the .py file extension, you tell VS Code to interpret this file as a Python program, so that it evaluates the contents with the Python extension and the selected interpreter.

Note: The File Explorer toolbar also allows you to create folders within your workspace to better organize your code. You can use the New folder button to quickly create a folder.

Now that you have a code file in your Workspace, enter the following source code in hello.py:

msg = "Hello World"
print(msg)

When you start typing print, notice how IntelliSense presents auto-completion options.

IntelliSense appearing for Python code

IntelliSense and auto-completions work for standard Python modules as well as other packages you’ve installed into the environment of the selected Python interpreter. It also provides completions for methods available on object types. For example, because the msg variable contains a string, IntelliSense provides string methods when you type msg.:

IntelliSense appearing for a variable whose type provides methods

Feel free to experiment with IntelliSense some more, but then revert your changes so you have only the msg variable and the print call, and save the file (⌘S (Windows, Linux Ctrl+S)).

For full details on editing, formatting, and refactoring, see Editing code. The Python extension also has full support for Linting.

Run Hello World

It’s simple to run hello.py with Python. Just click the Run Python File in Terminal play button in the top-right side of the editor.

Using the run python file in terminal button

The button opens a terminal panel in which your Python interpreter is automatically activated, then runs python3 hello.py (macOS/Linux) or python hello.py (Windows):

Program output in a Python terminal

There are three other ways you can run Python code within VS Code:

  • Right-click anywhere in the editor window and select Run Python File in Terminal (which saves the file automatically):

    Run Python File in Terminal command in the Python editor

  • Select one or more lines, then press Shift+Enter or right-click and select Run Selection/Line in Python Terminal. This command is convenient for testing just a part of a file.

  • From the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)), select the Python: Start REPL command to open a REPL terminal for the currently selected Python interpreter. In the REPL, you can then enter and run lines of code one at a time.

Configure and run the debugger

Let’s now try debugging our simple Hello World program.

First, set a breakpoint on line 2 of hello.py by placing the cursor on the print call and pressing F9. Alternately, just click in the editor’s left gutter, next to the line numbers. When you set a breakpoint, a red circle appears in the gutter.

Setting a breakpoint in hello.py

Next, to initialize the debugger, press F5. Since this is your first time debugging this file, a configuration menu will open from the Command Palette allowing you to select the type of debug configuration you would like for the opened file.

Debug configurations after launch.json is created

Note: VS Code uses JSON files for all of its various configurations; launch.json is the standard name for a file containing debugging configurations.

These different configurations are fully explained in Debugging configurations; for now, just select Python File, which is the configuration that runs the current file shown in the editor using the currently selected Python interpreter.

You can also start the debugger by clicking on the down-arrow next to the run button on the editor, and selecting Debug Python File in Terminal.

Using the debug Python file in terminal button

The debugger will stop at the first line of the file breakpoint. The current line is indicated with a yellow arrow in the left margin. If you examine the Local variables window at this point, you will see now defined msg variable appears in the Local pane.

Debugging step 2 - variable defined

A debug toolbar appears along the top with the following commands from left to right: continue (F5), step over (F10), step into (F11), step out (⇧F11 (Windows, Linux Shift+F11)), restart (⇧⌘F5 (Windows, Linux Ctrl+Shift+F5)), and stop (⇧F5 (Windows, Linux Shift+F5)).

Debugging toolbar

The Status Bar also changes color (orange in many themes) to indicate that you’re in debug mode. The Python Debug Console also appears automatically in the lower right panel to show the commands being run, along with the program output.

To continue running the program, select the continue command on the debug toolbar (F5). The debugger runs the program to the end.

Tip Debugging information can also be seen by hovering over code, such as variables. In the case of msg, hovering over the variable will display the string Hello world in a box above the variable.

You can also work with variables in the Debug Console (If you don’t see it, select Debug Console in the lower right area of VS Code, or select it from the menu.) Then try entering the following lines, one by one, at the > prompt at the bottom of the console:

msg
msg.capitalize()
msg.split()

Debugging step 3 - using the debug console

Select the blue Continue button on the toolbar again (or press F5) to run the program to completion. «Hello World» appears in the Python Debug Console if you switch back to it, and VS Code exits debugging mode once the program is complete.

If you restart the debugger, the debugger again stops on the first breakpoint.

To stop running a program before it’s complete, use the red square stop button on the debug toolbar (⇧F5 (Windows, Linux Shift+F5)), or use the Run > Stop debugging menu command.

For full details, see Debugging configurations, which includes notes on how to use a specific Python interpreter for debugging.

Tip: Use Logpoints instead of print statements: Developers often litter source code with print statements to quickly inspect variables without necessarily stepping through each line of code in a debugger. In VS Code, you can instead use Logpoints. A Logpoint is like a breakpoint except that it logs a message to the console and doesn’t stop the program. For more information, see Logpoints in the main VS Code debugging article.

Install and use packages

Let’s now run an example that’s a little more interesting. In Python, packages are how you obtain any number of useful code libraries, typically from PyPI. For this example, you use the matplotlib and numpy packages to create a graphical plot as is commonly done with data science. (Note that matplotlib cannot show graphs when running in the Windows Subsystem for Linux as it lacks the necessary UI support.)

Return to the Explorer view (the top-most icon on the left side, which shows files), create a new file called standardplot.py, and paste in the following source code:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 20, 100)  # Create a list of evenly-spaced numbers over the range
plt.plot(x, np.sin(x))       # Plot the sine of each x point
plt.show()                   # Display the plot

Tip: If you enter the above code by hand, you may find that auto-completions change the names after the as keywords when you press Enter at the end of a line. To avoid this, type a space, then Enter.

Next, try running the file in the debugger using the «Python: Current file» configuration as described in the last section.

Unless you’re using an Anaconda distribution or have previously installed the matplotlib package, you should see the message, «ModuleNotFoundError: No module named ‘matplotlib'». Such a message indicates that the required package isn’t available in your system.

To install the matplotlib package (which also installs numpy as a dependency), stop the debugger and use the Command Palette to run Terminal: Create New Terminal (⌃⇧` (Windows, Linux Ctrl+Shift+`)). This command opens a command prompt for your selected interpreter.

A best practice among Python developers is to avoid installing packages into a global interpreter environment. You instead use a project-specific virtual environment that contains a copy of a global interpreter. Once you activate that environment, any packages you then install are isolated from other environments. Such isolation reduces many complications that can arise from conflicting package versions. To create a virtual environment and install the required packages, enter the following commands as appropriate for your operating system:

Note: For additional information about virtual environments, see Environments.
v

  1. Create a virtual environment using the Create Environment command

    From within VS Code, you can create non-global environments, using Venv or Anaconda, by opening the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)), start typing the Python: Create Environment command to search, and then select the command. You can also trigger the Python: Create Environment command through the Getting Started with Python page.

    The command presents a list of environment types, Venv or Conda. For this example, select Venv.

    Create Environment dropdown

    The command then presents a list of interpreters that can be used for your project.

    Virtual environment interpreter selection

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

    Create environment status notification

    The command will also install necessary packages outlined in a requirements/dependencies file, such as requirements.txt, pyproject.toml, or environment.yml, located in the project folder.

    Note: If you want to create an environment manually, or run into error in the environment creation process, visit the Environments page.

  2. Ensure your new environment is selected by using the Python: Select Interpreter command from the Command Palette.

    Select an Interpreter

  3. Install the packages

    # Don't use with Anaconda distributions because they include matplotlib already.
    
    # macOS
    python3 -m pip install matplotlib
    
    # Windows (may require elevation)
    python -m pip install matplotlib
    
    # Linux (Debian)
    apt-get install python3-tk
    python3 -m pip install matplotlib
    
  4. Rerun the program now (with or without the debugger) and after a few moments a plot window appears with the output:

    matplotlib output

  5. Once you are finished, type deactivate in the terminal window to deactivate the virtual environment.

For additional examples of creating and activating a virtual environment and installing packages, see the Django tutorial and the Flask tutorial.

Next steps

You can configure VS Code to use any Python environment you have installed, including virtual and conda environments. You can also use a separate environment for debugging. For full details, see Environments.

To learn more about the Python language, follow any of the programming tutorials listed on python.org within the context of VS Code.

To learn to build web apps with the Django and Flask frameworks, see the following tutorials:

  • Use Django in Visual Studio Code
  • Use Flask in Visual Studio Code

There is then much more to explore with Python in Visual Studio Code:

  • Editing code — Learn about autocomplete, IntelliSense, formatting, and refactoring for Python.
  • Linting — Enable, configure, and apply a variety of Python linters.
  • 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.
  • Deploy Python to Azure App Service
  • Deploy Python to Container Apps

1/20/2023

Суперсет Python и Visual Studio Code в действии! Полное руководство по настройке и началу работы на лучшем языке в лучшем редакторе.

Python + Visual Studio Code = успешная разработка

VS Code от Microsoft – легкий и удобный редактор кода, доступный на всех платформах и невероятно гибкий. Это отличный выбор для программирования на Python.

В этой статье мы рассмотрим способы установки и настройки максимально эффективной рабочей среды для разработки.

Статья предназначена для программистов, уже имеющих опыт работы с Python и установивших на свою рабочую машину интерпретатор этого языка программирования (Python 2.7, Python 3.6/3.7, Anaconda или другой дистрибутив).

Установка Python – дело несложное: здесь вы найдете подробное пошаговое руководство для всех популярных ОС. Помните, что в разных операционных системах интерфейс VS Code может немного различаться.

Сразу же отметим, что VS Code не имеет практически ничего общего с его знаменитым тезкой Visual Studio.

Редактор очень легко установить на любую платформу: на официальном сайте есть подробные инструкции для Windows, Mac и Linux.

Продукт ежемесячно обновляется и улучшается. В него из коробки встроена поддержка нескольких языков и удобная модель расширения. Пользовательский интерфейс предельно прост и понятен.

VS Code + Python

С 2018 года есть расширение для Python. Наблюдать за развитием отношений этой пары можно в блоге Microsoft.

Основные возможности редактора:

  • Поддержка Python 3.4 и выше, а также Python 2.7
  • Автоматическое дополнение кода с помощью IntelliSense
  • Линтинг
  • Отладка
  • Сниппеты
  • Модульное тестирование
  • Автоматическое использование conda и виртуальных сред
  • Редактирование кода в средах Jupyter и Jupyter Notebooks

А вот пара полезных подборок для прокачки Python-скиллов:

  • Лучшие книги по Python: эффективно, емко, доходчиво
  • Крупнейшая подборка Python-каналов на Youtube

В редакторе есть и полезные фичи, не связанные напрямую с языком:

  • Наборы горячих клавиш для Atom, Sublime Text, Emacs, Vim, PyCharm и множества других редакторов
  • Настраиваемые темы оформления
  • Языковые пакеты для множества языков, включая русский

И еще несколько крутых возможностей для полного счастья:

  1. GitLens – множество полезных функций Git прямо в редакторе, включая аннотации blame и просмотр репозитория.
  2. Автосохранение (FileAuto Save) и удобная настройка его задержки.
  3. Синхронизация параметров редактора между различными устройствами с помощью GitHub.
  4. Удобная работа с Docker.

Чтобы найти и установить необходимые расширения и темы, нажмите на иконку Расширения на левой панели. Можно искать по ключевым словам и сортировать результаты поиска.

Найдите расширение Python и установите его, чтобы продолжить настройку редактора.

Файлы конфигурации

В Visual Studio Code вы легко можете настроить все под себя. Здесь есть параметры пользователя, которые являются глобальными, и параметры рабочей области – локальные для конкретных папок или проектов. Локальные настройки сохраняются в виде .json-файлов в папке .vscode.

Новый проект на Python

Чтобы открыть новый файл, нужно зайти в меню Файл и выбрать пункт Создать или нажать горячую комбинацию клавиш Ctrl+N.

Еще в редакторе есть полезная палитра команд, которую можно вызвать сочетанием Ctrl+Shift+P. Для создания нового файла введите в появившемся поле File: New File и нажмите Enter.

Какой бы способ вы ни выбрали, перед вами должно открыться вот такое окно:

Здесь уже можно вводить код вашей программы.

Начинаем кодить

Для демонстрации возможностей редактора напишем «Решето Эратосфена» – известный алгоритм для нахождения простых чисел до некоторого предела. Начнем кодить:

sieve = [True] * 101
for i in range(2, 100):

На экране это будет выглядеть примерно так:

Подождите, что-то не так. Почему-то VS Code не выделяет ключевые слова языка, не дополняет, не форматирует и вообще ничего полезного не делает. Зачем он вообще такой нужен?

Без паники! Просто сейчас редактор не знает, с каким файлом он имеет дело. Смотрите, у него еще нет названия и расширения – только какое-то неопределенное Untitled-1. А в правом нижнем углу написано Plain Text (простой текст).

Установка Python плагина уже произведена, теперь его нужно активировать. Для этого достаточно просто сохранить файл с нужным расширением. Для этого у нас опять же три способа:

  • меню: Файл — Сохранить
  • горячая комбинация: Ctrl+S
  • палитра команд: File: Save File

Дайте файлу имя sieve.py.

Теперь редактор понял, что имеет дело с кодом на Python, и исправился:

Так гораздо лучше! В правом нижнем углу появилась надпись Python, значит все работает правильно.

Если на вашем компьютере установлено несколько интерпретаторов языка (Python 2.7, Python 3.x или Anaconda), вы можете выбирать нужный. Для этого кликните на индикаторе языка (внизу в левой части экрана) или наберите в палитре команд Python: Select Interpreter.

По умолчанию VS Code поддерживает форматирование с использованием pep8, но вы можете выбрать black или yapf, если хотите.

Допишем код алгоритма:

sieve = [True] * 101
for i in range(2, 100):
if sieve[i]:
print(i)
for j in range(i*i, 100, i):
sieve[j] = False

Если вы будете вводить его вручную (без copy-paste), то сможете увидеть IntelliSense редактора в действии.

VS Code автоматически делает отступы перед операторами for и if, добавляет закрывающие скобки и предлагает варианты завершения слов.

Запуск программы

Чтобы запустить готовую программу, нам даже не нужно выходить из редактора! Просто сохраните файл, вызовите правой кнопкой мыши контекстное меню и выберите в нем пункт Выполнить файл в консоли.

Теперь, когда код завершен, его можно запустить. Для этого не нужно выходить из редактора: Visual Studio Code может запускать эту программу непосредственно в Редакторе. Сохраните файл (с помощью Ctrl+S), затем щелкните правой кнопкой мыши в окне редактора и выберите пункт Запустить файл Python в терминале.

В нижней части окна должна появиться панель терминала с результатом работы программы.

Линтинг кода

Возможно, вы уже успели увидеть всплывающее окно с сообщением, что проверка кода недоступна и предложением установить линтер. По умолчанию расширение предлагает PyLint. Также поддерживаются и другие инструменты:

  • flake8
  • mypy
  • pydocstyle
  • pep8
  • prospector
  • pyllama
  • bandit

Подробные сведения о настройке каждого из них вы можете найти здесь.

Обратите внимание, что линтер настраивается для конкретной рабочей области, а не глобально.

Редактирование существующего проекта

Итак, мы научились создавать новые файлы. Это здорово, но все же большую часть времени вам придется работать с уже существующими проектами, которые состоят из множества отдельных файлов и папок.

С редактором можно работать прямо из консоли, открывая и создавая файлы простой командой code filename.py.

Посмотрим, на что способен VS Code на примере уже готового проекта. Это библиотека для анализа уравнений, основанная на «алгоритме маневровой станции» (shunting-yard algorithm) Дийкстры. Вы можете клонировать этот репозиторий, чтобы начать работу.

Открыть созданную локально папку в редакторе можно из терминала:

cd /path/to/project
code .

VS Code умеет работать с различными средами:  virtualenv, pipenv или conda.

Также вы можете открыть папку прямо из интерфейса редактора:

  • меню: Файл — Открыть папку
  • горячие клавиши: Ctrl+K, Ctrl+O
  • из палитры команд: File: Open Folder

Вот так выглядит открытый проект:

По умолчанию при открытии папки VS Code также открывает файлы, с которыми вы работали в последний раз. Это поведение можно изменить.

Теперь вы можете открывать, редактировать, запускать и отлаживать все файлы проекта, перечисленные в левой панели. Над проводником отображаются все файлы, с которыми вы в данный момент работаете.

Тестирование

Грамотное программирование на Python помимо собственно написания кода включает также его тестирование.

Visual Studio Code умеет автоматически распознавать тесты в unittest, pytest или Nose. В нашем проекте есть модульный тест, который можно использовать для примера.

Чтобы запустить существующие тесты, из любого файла Python вызовите правой кнопкой мыши контекстное меню и выберите пункт Запустить текущий тестовый файл.

Нужно будет указать используемый для тестирования фреймворк, путь поиска и шаблон для имени файлов тестов. Эти настройки сохраняются как параметры рабочей области в локальном файле .vscode/settings.json. Для нашего проекта нужно выбрать unittest, текущую папку и шаблон *_test.py.

Теперь можно запустить все тесты, кликнув на Run Tests в строке состояния или из палитры команд.

Также тесты можно выполнять по отдельности, что позволяет экономить много времени, работая только с неудачными методами.

Результаты тестов отображаются во вкладке Output (раздел Python Test Log выпадающего меню).

Посмотрите также:

  • Погружаемся в основы и нюансы тестирования Python-кода

Отладка кода

Несмотря на то, что VS Code – это просто редактор кода, а не полноценная IDE, он позволяет отлаживать код Python прямо в рабочей области. У него есть много функций, которые должны быть у хорошего отладчика:

  • Автоматическое отслеживание переменных
  • Отслеживание выражений
  • Точки прерывания
  • Инспекция стека вызовов

Все эти данные можно найти во вкладке Debug левой панели.

Отладчик может управлять приложениями Python, запущенными во встроенной консоли или внешнем терминале. Он может подключаться к уже запущенным экземплярам Python и даже отлаживать приложения Django и Flask.

Отладить программу на Python так же просто, как запустить отладчик с помощью F5. Используйте F10 и F11 для перехода к следующей функции и для захода в текущую функцию. Shift+F5 – выход из отладчика. Точки останова задаются с помощью клавиши F9 или щелчком мыши в левом поле окна редактора.

Перед началом отладки более сложных проектов, включая приложения Django или Flask, необходимо настроить и выбрать конфигурацию отладки. Сделать это очень просто. Во вкладке Debug найдите раскрывающееся меню Configuration и нажмите Add Configuration:

VS Code создаст и откроет файл .vscode/launch.json, в котором можно настроить конфигурации Python, а также отладку приложений.

Вы даже можете выполнять удаленную отладку и дебажить шаблоны Jinja и Django. Закройте launch.json и выберите нужную конфигурацию приложения из раскрывающегося списка.

Посмотрите также:

  • Инструменты для анализа кода Python. Часть 1 и Часть 2

Интеграция с Git

В VS Code прямо из коробки есть встроенная поддержка управления версиями. По умолчанию подключен Git и GitHub, но вы можете установить поддержку других систем. Все работа происходит во вкладке Source Control левого меню:

Если в проекте есть папка .git, весь спектр функций Git/GitHub включается автоматически. Вы можете:

  • Коммитить файлы
  • Обновлять проект из удаленного репозитория, и отправлять туда свои изменения
  • Работать с существующими ветками и тегами и создавать новые
  • Просматривать и разрешать конфликты слияния
  • Просматривать диффы

Все эти функции доступны прямо из пользовательского интерфейса:

VS Code также распознает изменения, внесенные вне редактора.

Все измененные файлы помечены маркером M, а неотслеживаемые – U. Символ + подготавливает файлы к коммиту. Чтобы сохранить изменения, введите сообщение и нажмите галочку.

Локальные коммиты можно отправить на GitHub прямо из редактора. Выберите в меню пункт Sync или кликните по значку Synchronize Changes в статус-баре в самом низу редактора (рядом с индикатором текущей ветки).

Visual Studio Code + Python = довольный разработчик

Visual Studio Code – один из самых крутых редакторов кода и замечательный инструмент для разработки. Редактор из коробки предлагает множество полезных возможностей и гибко подстраивается под все ваши потребности. Программирование на Python становится проще и эффективнее.

А какой редактор (или полноценную IDE) для разработки на Python используете вы?

Оригинал статьи: Python Development in Visual Studio Code

Полезные статьи и книги по Python:

    • ООП на Python: концепции, принципы и примеры реализации
    • Самые эффективные ресурсы и материалы для изучения Python
    • 100+ крутых проектов, созданных с помощью Python

Последние несколько лет специалисты Microsoft трудились над тем, чтобы добавить поддержку инструментов разработчика Python в одни из наших самых популярных продуктов: Visual Studio Code и Visual Studio. В этом году все заработало. В статье мы познакомимся с инструментами разработчика Python в Visual Studio, Visual Studio Code, Azure и т. д. Заглядывайте под кат!

Python — один из самых быстро развивающихся языков программирования, к которому обращаются как начинающие, так и опытные разработчики. Его популярность обусловлена легкой в освоении семантикой и широким спектром применения, начиная от написания скриптов и заканчивая созданием веб-сервисов и моделей машинного обучения.

Дополнительную информацию и последние новости о Python в Microsoft вы можете найти в блоге Python at Microsoft.

Visual Studio Code

Расширение Python для Visual Studio Code с открытым исходным кодом включает в себя другие общедоступные пакеты Python, чтобы предоставить разработчикам широкие возможности для редактирования, отладки и тестирования кода. Python — самый быстроразвивающийся язык в Visual Studio Code, а соответствующее расширение является одним из самых популярных в разделе Marketplace, посвященном Visual Studio Code!

Чтобы начать работу с расширением, необходимо сначала скачать Visual Studio Code, а затем, следуя нашему руководству Начало работы с Python, установить расширение и настроить основные функции. Рассмотрим некоторые из них.

Прежде всего необходимо убедиться, что Visual Studio Code использует правильный интерпретатор Python. Чтобы сменить интерпретатор, достаточно выбрать нужную версию Python в строке состояния:

Селектор поддерживает множество разных интерпретаторов и сред Python: Python 2, 3, virtualenv, Anaconda, Pipenv и pyenv. После выбора интерпретатора расширение начнет использовать его для функции IntelliSense, рефакторинга, анализа, выполнения и отладки кода.

Чтобы локально запустить скрипт Python, можно воспользоваться командой «Python: Create Terminal» («Python: создать терминал») для создания терминала с активированной средой. Нажмите CTRL + Shift + P (или CMD + Shift + P на Mac), чтобы открыть командную строку. Чтобы выполнить файл Python, достаточно щелкнуть на нем правой кнопкой мыши и выбрать пункт «Run Python File in Terminal» («Запустить файл Python в терминале»):

Эта команда запустит выбранный интерпретатор Python, в данном случае виртуальную среду Python 3.6, для выполнения файла:

Расширение Python также включает шаблоны отладки для многих популярных типов приложений. Перейдите на вкладку «Debug» («Отладка») и выберите «Add Configuration…» («Добавить конфигурацию…») в выпадающем меню конфигурации отладки:

Вы увидите готовые конфигурации для отладки текущего файла, подключающегося к удаленному серверу отладки или соответствующему приложению Flask, Django, Pyramid, PySpark или Scrapy. Для запуска отладки нужно выбрать конфигурацию и нажать зеленую кнопку Play (или клавишу F5 на клавиатуре, FN + F5 на Mac).

Расширение Python поддерживает различные анализаторы кода, для которых можно настроить запуск после сохранения файла Python. PyLint включен по умолчанию, а другой анализатор можно выбрать с помощью команды «Python: Select Linter» («Python: выбрать анализатор кода»):

Это еще не все: предусмотрена поддержка рефакторинга, а также модульного тестирования с помощью unittest, pytest и nose. К тому же вы можете использовать Visual Studio Live Share для удаленной работы над кодом Python вместе с другими разработчиками!

Python в Visual Studio

Visual Studio поддерживает большую часть функций Visual Studio Code, но также предлагает все полезные возможности интегрированной среды разработки, что позволяет совершать больше операций без использования командной строки. Visual Studio также предоставляет не имеющие равных возможности для работы с гибридными проектами Python и C# или C++.

Чтобы включить поддержку Python в Visual Studio на Windows, необходимо выбрать рабочую нагрузку «Разработка на Python» и (или) рабочую нагрузку «Приложения для обработки и анализа данных и аналитические приложения» в установщике Visual Studio:

Можно установить различные версии Python и Anaconda, выбрав их в меню дополнительных компонентов (см. правую часть скриншота выше).

После установки рабочей нагрузки Python, можно начать работу, создав проект Python в разделе с помощью меню «Файл -> Новый проект» (в списке установленных компонентов выберите Python):

Чтобы создать приложение с нуля, откройте шаблон приложения Python и приступайте к написанию кода. Также можно создать проект, взяв за основу существующий код Python или используя веб-шаблоны для Flask, Django и Bottle. Ознакомьтесь с нашим Руководством по Flask и Руководством по Django, чтобы получить подробную информацию по разработке веб-приложений с помощью этих платформ и Visual Studio.

Если установлена рабочая нагрузка по обработке и анализу данных, также можно использовать шаблоны для проектов по машинному обучению с использованием Tensorflow и CNTK.
После того как проект создан, управлять виртуальными средами и средами conda можно с помощью узла «Python Environments» («Среды Python») в обозревателе решений и окне среды Python. Щелкнув правой кнопкой мыши по активной среде Python и выбрав соответствующий пункт меню, можно установить дополнительные пакеты:

Visual Studio по-настоящему демонстрирует свои возможности при использовании Python с другими языками. Можно объединять проекты Python и C++ для создания решения или даже встраивать файлы .py в проекты C++ или C#!

Можно даже проводить отладку кода на обоих языках в рамках одного сеанса, например, переключившись с типа отладки C++ на Python/Native:

Ознакомиться с подробной информацией о вставке Python в приложения C++ можно в публикации Вставка Python в проект C++ в блоге Python.

Кроме того, Visual Studio включает профилировщик Python и поддерживает модульное тестирование Python в Обозревателе тестов.

Python в Azure

Пакет Azure SDK для Python позволяет создавать службы в Azure, управлять ими и взаимодействовать с ними. Командная строка Azure CLI написана на Python, поэтому почти все, что она позволяет сделать, вы можете также выполнить на программном уровне с помощью пакета Python SDK.

Можно устанавливать отдельные библиотеки, например для установки пакета SDK для взаимодействия с Azure Storage воспользуйтесь командой:

    pip install azure-storage

Рекомендуется устанавливать только нужные вам пакеты, но для удобства вы можете установить весь набор пакетов Azure SDK, выполнив следующую команду:

    pip install azure

После установки пакета SDK вы получаете доступ ко множеству полезных служб, начиная от использования API машинного обучения с помощью Azure Cognitive Services и заканчивая размещением глобально распределенных данных с помощью Azure Cosmos DB.

Веб-приложения можно развернуть с помощью функции Azure «Веб-приложение для контейнеров». Ознакомьтесь с видео From Zero to Azure with Python and Visual Studio Code (В Azure с нуля с помощью Python и Visual Studio Code), предоставляющим всю необходимую информацию по развертыванию приложений Flask с использованием Visual Studio Code. Также обратите внимание на краткое пособие по развертыванию приложения Flask с использованием командной строки.

Кроме того, на Azure можно запускать свободно размещенные блокноты Jupyter, поэтому локальная установка Jupyter не потребуется. К блокнотам Jupyter можно открывать доступ для их совместного использования. Например, вы можете просмотреть находящийся в общем доступе блокнот для создания рукописного текста с помощью машинного обучения:

Войдите в учетную запись на notebooks.azure.com, чтобы опробовать клонирование и запуск блокнотов Jupyter!

Полезные материалы по теме

Мини-книга «Создавайте более качественные приложения и быстро используйте данные там, где это нужно»

Читайте электронную книгу Создание современных приложений на основе больших данных в глобальном масштабе, чтобы узнать, как готовая к использованию глобально распределенная служба баз данных Azure Cosmos DB меняет подходы к управлению данными. Обеспечивайте доступность, согласованность и защиту данных, используя передовые отраслевые технологии корпоративного класса для соблюдения нормативных требований и обеспечения безопасности. Начните разработку лучших приложений для своих пользователей на базе одной из пяти четко определенных моделей согласованности.

Скачать

Семинар «Как выбрать правильную инфраструктуру для выполнения ваших рабочих нагрузок в Azure»

В этом семинаре присоединитесь к рассказу регионального директора Microsoft Эрику Бойду, MVP Azure, о том, как выбрать правильные виртуальные машины, хранилища и сети для приложений и рабочих нагрузок в Azure.

Скачать/Посмотреть

Руководство по архитектуре облачных приложений

Используйте структурированный подход к разработке облачных приложений. В этой 300-страничной электронной книге об архитектуре облачных вычислений рассматриваются рекомендации по архитектуре, разработке и внедрению, которые применяются независимо от выбранной облачной платформы. В это руководство включены шаги по:

  • выбору правильного стиля архитектуры облачного приложения для своего приложения или решения;
  • выбору соответствующих технологий вычислений и хранения данных;
  • внедрению 10 принципов разработки для создания масштабируемого, отказоустойчивого и управляемого приложения;
  • следованию пяти принципам создания качественного программного обеспечения, гарантирующего успех вашего облачного приложения;
  • использованию конструктивных шаблонов, предназначенных для проблемы, которую вы пытаетесь решить.

Скачать

One of the coolest code editors available to programmers, Visual Studio Code, is an open-source, extensible, light-weight editor available on all platforms. It’s these qualities that make Visual Studio Code from Microsoft very popular, and a great platform for Python development.

In this article, you’ll learn about Python development in Visual Studio Code, including how to:

  • Install Visual Studio Code
  • Discover and install extensions that make Python development easy
  • Write a straightforward Python application
  • Learn how to run and debug existing Python programs in VS Code
  • Connect Visual Studio Code to Git and GitHub to share your code with the world

We assume you are familiar with Python development and already have some form of Python installed on your system (Python 2.7, Python 3.6/3.7, Anaconda, or others). Screenshots and demos for Ubuntu and Windows are provided. Because Visual Studio Code runs on all major platforms, you may see slightly different UI elements and may need to modify certain commands.

If you already have a basic VS Code setup and you’re hoping to dig deeper than the goals in this tutorial, you might want to explore some advanced features in VS Code.

Installing and Configuring Visual Studio Code for Python Development

Installing Visual Studio Code is very accessible on any platform. Full instructions for Windows, Mac, and Linux are available, and the editor is updated monthly with new features and bug fixes. You can find everything at the Visual Studio Code website:

Visual Studio Code Web Site

In case you were wondering, Visual Studio Code (or VS Code for short) shares almost nothing other than a name with its larger Windows-based namesake, Visual Studio.

Visual Studio Code has built-in support for multiple languages and an extension model with a rich ecosystem of support for others. VS Code is updated monthly, and you can keep up to date at the Microsoft Python blog. Microsoft even makes the VS Code GitHub repo available for anyone to clone and contribute. (Cue the PR flood.)

The VS Code UI is well documented, so I won’t rehash it here:

Visual Studio Code Welcome Screen

Extensions for Python Development

As stated above, VS Code supports development in multiple programming languages through a well-documented extension model. The Python extension enables Python development in Visual Studio Code, with the following features:

  • Support for Python 3.4 and higher, as well as Python 2.7
  • Code completion with IntelliSense
  • Linting
  • Debugging support
  • Code snippets
  • Unit testing support
  • Automatic use of conda and virtual environments
  • Code editing in Jupyter environments and Jupyter Notebooks

Installing the Python extension for VSCode

Visual Studio Code extensions cover more than just programming language capabilities:

  • Keymaps allow users already familiar with Atom, Sublime Text, Emacs, Vim, PyCharm, or other environments to feel at home.

  • Themes customize the UI whether you like coding in the light, dark, or something more colorful.

  • Language packs provide a localized experience.

Here are some other extensions and settings I find useful:

  • GitLens provides tons of useful Git features directly in your editing window, including blame annotations and repository exploration features.

  • Auto save is easily turned on by selecting File, Auto Save from the menu. The default delay time is 1000 milliseconds, which is also configurable.

  • Settings Sync allows you to synchronize your VS Code settings across different installations using GitHub. If you work on different machines, this helps keep your environment consistent across them.

  • Docker lets you quickly and easily work with Docker, helping author Dockerfile and docker-compose.yml, package and deploy your projects, and even generate the proper Docker files for your project.

Of course, you may discover other useful extensions as you use VS Code. Please share your discoveries and settings in the comments!

Discovering and installing new extensions and themes is accessible by clicking on the Extensions icon on the Activity Bar. You can search for extensions using keywords, sort the results numerous ways, and install extensions quickly and easily. For this article, install the Python extension by typing python in the Extensions item on the Activity Bar, and clicking Install:

Finding the VSCode Marketplace in the UI

You can find and install any of the extensions mentioned above in the same manner.

Visual Studio Code Configuration Files

One important thing to mention is that Visual Studio Code is highly configurable through user and workspace settings.

User settings are global across all Visual Studio Code instances, while workspace settings are local to the specific folder or project workspace. Workspace settings give VS Code tons of flexibility, and I call out workspace settings throughout this article. Workspace settings are stored as .json files in a folder local to the project workspace called .vscode.

Start a New Python Program

Let’s start our exploration of Python development in Visual Studio Code with a new Python program. In VS Code, type Ctrl+N to open a new File. (You can also select File, New from the menu.)

No matter how you get there, you should see a VS Code window that looks similar to the following:

Creating a new file in VSCode

Once a new file is opened, you can begin entering code.

Entering Python Code

For our test code, let’s quickly code up the Sieve of Eratosthenes (which finds all primes less than a given number). Begin typing the following code in the new tab you just opened:

sieve = [True] * 101
for i in range(2, 100):

You should see something similar to this:

Unformatted code in VSCode

Wait, what’s going on? Why isn’t Visual Studio Code doing any keyword highlighting, any auto-formatting, or anything really helpful? What gives?

The answer is that, right now, VS Code doesn’t know what kind of file it’s dealing with. The buffer is called Untitled-1, and if you look in the lower right corner of the window, you’ll see the words Plain Text.

To activate the Python extension, save the file (by selecting File, Save from the menu, File:Save File from the Command Palette, or just using Ctrl+S) as sieve.py. VS Code will see the .py extension and correctly interpret the file as Python code. Now your window should look like this:

Properly formatted Python code in VSCode

That’s much better! VS Code automatically reformats the file as Python, which you can verify by inspecting the language mode in the lower left corner.

If you have multiple Python installations (like Python 2.7, Python 3.x, or Anaconda), you can change which Python interpreter VS Code uses by clicking the language mode indicator, or selecting Python: Select Interpreter from the Command Palette. VS Code supports formatting using pep8 by default, but you can select black or yapf if you wish.

Let’s add the rest of the Sieve code now. To see IntelliSense at work, type this code directly rather than cut and paste, and you should see something like this:

Typing the Sieve of Eratosthenes Python code

Here’s the full code for a basic Sieve of Eratosthenes:

sieve = [True] * 101
for i in range(2, 100):
    if sieve[i]:
        print(i)
        for j in range(i*i, 100, i):
            sieve[j] = False

As you type this code, VS Code automatically indents the lines under for and if statements for you properly, adds closing parentheses, and makes suggestions for you. That’s the power of IntelliSense working for you.

Running Python Code

Now that the code is complete, you can run it. There is no need to leave the editor to do this: Visual Studio Code can run this program directly in the editor. Save the file (using Ctrl+S), then right-click in the editor window and select Run Python File in Terminal:

You should see the Terminal pane appear at the bottom of the window, with your code output showing.

Python Linting Support

You may have seen a pop up appear while you were typing, stating that linting was not available. You can quickly install linting support from that pop up, which defaults to PyLint. VS Code also supports other linters. Here’s the complete list at the time of this writing:

  • pylint
  • flake8
  • mypy
  • pydocstyle
  • pep8
  • prospector
  • pyllama
  • bandit

The Python linting page has complete details on how to setup each linter.

Editing an Existing Python Project

In the Sieve of Eratosthenes example, you created a single Python file. That’s great as an example, but many times, you’ll create larger projects and work on them over a longer period of time. A typical new project work flow might look like this:

  • Create a folder to hold the project (which may include a new GitHub project)
  • Change to the new folder
  • Create the initial Python code using the command code filename.py

Using Visual Studio Code on a Python project (as opposed to a single Python file) opens up tons more functionality that lets VS Code truly shine. Let’s take a look at how it works with a larger project.

Late in the previous millennium, when I was a much younger programmer, I wrote a calculator program that parsed equations written in infix notation, using an adaptation of Edsger Dijkstra’s shunting yard algorithm.

To demonstrate the project-focused features of Visual Studio Code, I began recreating the shunting yard algorithm as an equation evaluation library in Python. To continue following along, feel free to clone the repo locally.

Once the folder is created locally, you can open the entire folder in VS Code quickly. My preferred method (as mentioned above) is modified as follows, since I already have the folder and basic files created:

cd /path/to/project
code .

VS Code understands, and will use, any virtualenv, pipenv, or conda environments it sees when opened this way. You don’t even need to start the virtual environment first! You can even open a folder from the UI, using File, Open Folder from the menu, Ctrl+K, Ctrl+O from the keyboard, or File:Open Folder from the Command Palette.

For my equation eval library project, here’s what I see:

PyEval folder open in VSCode

When Visual Studio Code opens the folder, it also opens the files you last had opened. (This is configurable.) You can open, edit, run, and debug any file listed. The Explorer view in the Activity Bar on the left gives you a view of all the files in the folder and shows how many unsaved files exist in the current set of tabs.

Testing Support

VS Code can automatically recognize existing Python tests written in the unittest framework, or the pytest or Nose frameworks if those frameworks are installed in the current environment. I have a unit test written in unittest for the equation eval library, which you can use for this example.

To run your existing unit tests, from any Python file in the project, right-click and select Run Current Unit Test File. You’ll be prompted to specify the test framework, where in the project to search for tests, and the filename pattern your tests utilize.

All of these are saved as workspace settings in your local .vscode/settings.json file and can be modified there. For this equation project, you select unittest, the current folder, and the pattern *_test.py.

Once the test framework is set up and the tests have been discovered, you can run all your tests by clicking Run Tests on the Status Bar and selecting an option from the Command Palette:

You can even run individual tests by opening the test file in VS Code, clicking Run Tests on the Status Bar, and selecting the Run Unit Test Method… and the specific test to run. This makes it trivial to address individual test failures and re-run only failed tests, which is a huge time-saver! Test results are shown in the Output pane under Python Test Log.

Debugging Support

Even though VS Code is a code editor, debugging Python directly within VS Code is possible. VS Code offers many of the features you would expect from a good code debugger, including:

  • Automatic variable tracking
  • Watch expressions
  • Breakpoints
  • Call stack inspection

You can see them all as part of the Debug view on the Activity Bar:

Finding the Debug UI in VSCode

The debugger can control Python apps running in the built-in terminal or an external terminal instance. It can attach to an already running Python instances, and can even debug Django and Flask apps.

Debugging code in a single Python file is as simple as starting the debugger using F5. You use F10 and F11 to step over and into functions respectively, and Shift+F5 to exit the debugger. Breakpoints are set using F9, or using the mouse by clicking in the left margin in the editor window.

Before you start debugging more complicated projects, including Django or Flask applications, you need to setup and then select a debug configuration. Setting up the debug configuration is relatively straightforward. From the Debug view, select the Configuration drop-down, then Add Configuration, and select Python:

Adding a new debug configuration to VSCode

Visual Studio Code will create a debug configuration file under the current folder called .vscode/launch.json, which allows you to setup specific Python configurations as well as settings for debugging specific apps, like Django and Flask.

You can even perform remote debugging, and debug Jinja and Django templates. Close the launch.json file in the editor and select the proper configuration for your application from the Configuration drop-down.

Git Integration

VS Code has built-in support for source control management, and ships with support for Git and GitHub right out of the box. You can install support for other SCM’s in VS Code, and use them side by side. Source control is accessible from the Source Control view:

Source Control UI in VSCode

If your project folder contains a .git folder, VS Code automatically turns on the full range of Git/GitHub functionality. Here are some of the many tasks you can perform:

  • Commit files to Git
  • Push changes to, and pull changes from, remote repos
  • Check-out existing or create new branches and tags
  • View and resolve merge conflicts
  • View diffs

All of this functionality is available directly from the VS Code UI:

Git Commands in VSCode

VS Code will also recognize changes made outside the editor and behave appropriately.

Committing your recent changes within VS Code is a fairly straightforward process. Modified files are shown in the Source Control view with an M marker, while new untracked files are marked with a U. Stage your changes by hovering over the file and then clicking the plus sign (+). Add a commit message at the top of the view, and then click the check mark to commit the changes:

Committing changes in VSCode

You can push local commits to GitHub from within VS Code as well. Select Sync from the Source Control view menu, or click Synchronize Changes on the status bar next to the branch indicator.

Conclusion

Visual Studio Code is one of the coolest general purpose editors and a great candidate for Python development. In this article, you learned:

  • How to install VS Code on any platform
  • How to find and install extensions to enable Python-specific features
  • How VS Code makes writing a simple Python application easier
  • How to run and debug existing Python programs within VS Code
  • How to work with Git and GitHub repositories from VS Code

Visual Studio Code has become my default editor for Python and other tasks, and I hope you give it a chance to become yours as well.

If you have questions or comments, please reach out in the comments below. There is also a lot more information at the Visual Studio Code website than we could cover here.

The author sends thanks to Dan Taylor from the Visual Studio Code team at Microsoft for his time and invaluable input in this article.

python logo

Хочешь знать больше о Python?

Подпишись на наш канал о Python в Telegram!

Подписаться

×

Суперсет Python и Visual Studio Code в действии! Полное руководство по настройке и началу работы на лучшем языке в лучшем редакторе опубликовал сайт proglib.io.

Python и Visual Studio Code

VS Code от Microsoft – легкий и удобный редактор кода, доступный на всех платформах и невероятно гибкий. Это отличный выбор для программирования на Python.

В этой статье мы рассмотрим способы установки и настройки максимально эффективной рабочей среды для разработки.

Статья предназначена для программистов, уже имеющих опыт работы с Python и установивших на свою рабочую машину интерпретатор этого языка программирования (Python 2.7, Python 3.6/3.7, Anaconda или другой дистрибутив).

Установка Python – дело несложное: здесь вы найдете подробное пошаговое руководство для всех популярных ОС. Помните, что в разных операционных системах интерфейс VS Code может немного различаться.

Сразу же отметим, что VS Code не имеет практически ничего общего с его знаменитым тезкой Visual Studio.

Редактор очень легко установить на любую платформу: на официальном сайте есть подробные инструкции для Windows, Mac и Linux.

Официальный сайт VS Code

Продукт ежемесячно обновляется и улучшается. В него из коробки встроена поддержка нескольких языков и удобная модель расширения. Пользовательский интерфейс предельно прост и понятен.

пользовательский интерфейс VS Code

VS Code + Python

С 2018 года есть расширение для Python. Наблюдать за развитием отношений этой пары можно в блоге Microsoft.

Основные возможности редактора:

Поддержка Python 3.4 и выше, а также Python 2.7

  • Автоматическое дополнение кода с помощью IntelliSense
  • Линтинг
  • Отладка
  • Сниппеты
  • Модульное тестирование
  • Автоматическое использование conda и виртуальных сред
  • Редактирование кода в средах Jupyter и Jupyter Notebooks
Расширения VS Code для Python

А вот пара полезных подборок для прокачки Python-скиллов:

  • Лучшие книги по Python: эффективно, емко, доходчиво
  • Крупнейшая подборка Python-каналов на Youtube

В редакторе есть и полезные фичи, не связанные напрямую с языком:

  • Наборы горячих клавиш для Atom, Sublime Text, Emacs, Vim, PyCharm и множества других редакторов
  • Настраиваемые темы оформления
  • Языковые пакеты для множества языков, включая русский

И еще несколько крутых возможностей для полного счастья:

  1. GitLens – множество полезных функций Git прямо в редакторе, включая аннотации blame и просмотр репозитория.
  2. Автосохранение (File — Auto Save) и удобная настройка его задержки.
  3. Синхронизация параметров редактора между различными устройствами с помощью GitHub.
  4. Удобная работа с Docker.

Чтобы найти и установить необходимые расширения и темы, нажмите на иконку Расширения на левой панели. Можно искать по ключевым словам и сортировать результаты поиска.

Найдите расширение Python и установите его, чтобы продолжить настройку редактора.

Файлы конфигурации

В Visual Studio Code вы легко можете настроить все под себя. Здесь есть параметры пользователя, которые являются глобальными, и параметры рабочей области – локальные для конкретных папок или проектов. Локальные настройки сохраняются в виде .json-файлов в папке .vscode.

Новый проект на Python

Чтобы открыть новый файл, нужно зайти в меню Файл и выбрать пункт Создать или нажать горячую комбинацию клавиш Ctrl+N.

Еще в редакторе есть полезная палитра команд, которую можно вызвать сочетанием Ctrl+Shift+P. Для создания нового файла введите в появившемся поле File: New File и нажмите Enter.

Какой бы способ вы ни выбрали, перед вами должно открыться вот такое окно:

Окно нового проекта

Здесь уже можно вводить код вашей программы.

Начинаем кодить

Для демонстрации возможностей редактора напишем «Решето Эратосфена» – известный алгоритм для нахождения простых чисел до некоторого предела. Начнем кодить:

[python]sieve = [True] * 101
for i in range(2, 100):
[/python]

На экране это будет выглядеть примерно так:

Код нового проекта

Подождите, что-то не так. Почему-то VS Code не выделяет ключевые слова языка, не дополняет, не форматирует и вообще ничего полезного не делает. Зачем он вообще такой нужен?

Без паники! Просто сейчас редактор не знает, с каким файлом он имеет дело. Смотрите, у него еще нет названия и расширения – только какое-то неопределенное Untitled-1. А в правом нижнем углу написано Plain Text (простой текст).

Установка Python плагина уже произведена, теперь его нужно активировать. Для этого достаточно просто сохранить файл с нужным расширением. Для этого у нас опять же три способа:

  • меню: Файл — Сохранить
  • горячая комбинация: Ctrl+S
  • палитра команд: File: Save File

Дайте файлу имя sieve.py.

Теперь редактор понял, что имеет дело с кодом на Python, и исправился:

Редактор распознал Python

Так гораздо лучше! В правом нижнем углу появилась надпись Python, значит все работает правильно.

Если на вашем компьютере установлено несколько интерпретаторов языка (Python 2.7, Python 3.x или Anaconda), вы можете выбирать нужный. Для этого кликните на индикаторе языка (внизу в левой части экрана) или наберите в палитре команд Python: Select Interpreter.

По умолчанию VS Code поддерживает форматирование с использованием pep8, но вы можете выбрать black или yapf, если хотите.

Допишем код алгоритма:

[python]sieve = [True] * 101
for i in range(2, 100):
if sieve[i]:
print(i)
for j in range(i*i, 100, i):
sieve[j] = False
[/python]

Если вы будете вводить его вручную (без copy-paste), то сможете увидеть IntelliSense редактора в действии.

IntelliSense

VS Code автоматически делает отступы перед операторами for и if, добавляет закрывающие скобки и предлагает варианты завершения слов.

Запуск программы

Чтобы запустить готовую программу, нам даже не нужно выходить из редактора! Просто сохраните файл, вызовите правой кнопкой мыши контекстное меню и выберите в нем пункт Выполнить файл в консоли.

Теперь, когда код завершен, его можно запустить. Для этого не нужно выходить из редактора: Visual Studio Code может запускать эту программу непосредственно в Редакторе. Сохраните файл (с помощью Ctrl+S), затем щелкните правой кнопкой мыши в окне редактора и выберите пункт Запустить файл Python в терминале.

В нижней части окна должна появиться панель терминала с результатом работы программы.

Линтинг кода

Возможно, вы уже успели увидеть всплывающее окно с сообщением, что проверка кода недоступна и предложением установить линтер. По умолчанию расширение предлагает PyLint. Также поддерживаются и другие инструменты:

  • flake8
  • mypy
  • pydocstyle
  • pep8
  • prospector
  • pyllama
  • bandit

Подробные сведения о настройке каждого из них вы можете найти здесь.

Обратите внимание, что линтер настраивается для конкретной рабочей области, а не глобально.

Редактирование существующего проекта

Итак, мы научились создавать новые файлы. Это здорово, но все же большую часть времени вам придется работать с уже существующими проектами, которые состоят из множества отдельных файлов и папок.

С редактором можно работать прямо из консоли, открывая и создавая файлы простой командой code filename.py.

Посмотрим, на что способен VS Code на примере уже готового проекта. Это библиотека для анализа уравнений, основанная на «алгоритме маневровой станции» (shunting-yard algorithm) Дийкстры. Вы можете клонировать этот репозиторий, чтобы начать работу.

Открыть созданную локально папку в редакторе можно из терминала:

[python]cd /path/to/project
code .[/python]

VS Code умеет работать с различными средами:  virtualenv, pipenv или conda.

Также вы можете открыть папку прямо из интерфейса редактора:

  • меню: Файл — Открыть папку
  • горячие клавиши: Ctrl+KCtrl+O
  • из палитры команд: File: Open Folder

Вот так выглядит открытый проект:

Открытый проект

По умолчанию при открытии папки VS Code также открывает файлы, с которыми вы работали в последний раз. Это поведение можно изменить.

Теперь вы можете открывать, редактировать, запускать и отлаживать все файлы проекта, перечисленные в левой панели. Над проводником отображаются все файлы, с которыми вы в данный момент работаете.

Тестирование

Грамотное программирование на Python помимо собственно написания кода включает также его тестирование.

Visual Studio Code умеет автоматически распознавать тесты в unittestpytest или Nose. В нашем проекте есть модульный тест, который можно использовать для примера.

Чтобы запустить существующие тесты, из любого файла Python вызовите правой кнопкой мыши контекстное меню и выберите пункт Запустить текущий тестовый файл.

Нужно будет указать используемый для тестирования фреймворк, путь поиска и шаблон для имени файлов тестов. Эти настройки сохраняются как параметры рабочей области в локальном файле .vscode/settings.json. Для нашего проекта нужно выбрать unittest, текущую папку и шаблон *_test.py.

Теперь можно запустить все тесты, кликнув на Run Tests в строке состояния или из палитры команд.

Также тесты можно выполнять по отдельности, что позволяет экономить много времени, работая только с неудачными методами.

Результаты тестов отображаются во вкладке Output (раздел Python Test Log выпадающего меню).

Посмотрите также:

  • Погружаемся в основы и нюансы тестирования Python-кода

Отладка кода

Несмотря на то, что VS Code – это просто редактор кода, а не полноценная IDE, он позволяет отлаживать код Python прямо в рабочей области. У него есть много функций, которые должны быть у хорошего отладчика:

  • Автоматическое отслеживание переменных
  • Отслеживание выражений
  • Точки прерывания
  • Инспекция стека вызовов

Все эти данные можно найти во вкладке Debug левой панели.

Вкладка Debug левой панели

Отладчик может управлять приложениями Python, запущенными во встроенной консоли или внешнем терминале. Он может подключаться к уже запущенным экземплярам Python и даже отлаживать приложения Django и Flask.

Отладить программу на Python так же просто, как запустить отладчик с помощью F5. Используйте F10 и F11 для перехода к следующей функции и для захода в текущую функцию. Shift+F5 – выход из отладчика. Точки останова задаются с помощью клавиши F9 или щелчком мыши в левом поле окна редактора.

Перед началом отладки более сложных проектов, включая приложения Django или Flask, необходимо настроить и выбрать конфигурацию отладки. Сделать это очень просто. Во вкладке Debug найдите раскрывающееся меню Configuration и нажмите Add Configuration:

Раскрывающееся меню Configuration

VS Code создаст и откроет файл .vscode/launch.json, в котором можно настроить конфигурации Python, а также отладку приложений.

Вы даже можете выполнять удаленную отладку и дебажить шаблоны Jinja и Django. Закройте launch.json и выберите нужную конфигурацию приложения из раскрывающегося списка.

Посмотрите также:

  • Инструменты для анализа кода Python. Часть 1 и Часть 2

Интеграция с Git

В VS Code прямо из коробки есть встроенная поддержка управления версиями. По умолчанию подключен Git и GitHub, но вы можете установить поддержку других систем. Все работа происходит во вкладке Source Control левого меню:

Вкладка Source Control

Если в проекте есть папка .git, весь спектр функций Git/GitHub включается автоматически. Вы можете:

  • Коммитить файлы
  • Обновлять проект из удаленного репозитория, и отправлять туда свои изменения
  • Работать с существующими ветками и тегами и создавать новые
  • Просматривать и разрешать конфликты слияния
  • Просматривать диффы

Все эти функции доступны прямо из пользовательского интерфейса:

Функции Git, доступные из пользовательского интерфейса

VS Code также распознает изменения, внесенные вне редактора.

Все измененные файлы помечены маркером M, а неотслеживаемые – U. Символ + подготавливает файлы к коммиту. Чтобы сохранить изменения, введите сообщение и нажмите галочку.

Изменения, внесенные вне редактора

Локальные коммиты можно отправить на GitHub прямо из редактора. Выберите в меню пункт Syncили кликните по значку Synchronize Changes в статус-баре в самом низу редактора (рядом с индикатором текущей ветки).

Visual Studio Code + Python = довольный разработчик

Visual Studio Code – один из самых крутых редакторов кода и замечательный инструмент для разработки. Редактор из коробки предлагает множество полезных возможностей и гибко подстраивается под все ваши потребности. Программирование на Python становится проще и эффективнее.

А какой редактор (или полноценную IDE) для разработки на Python используете вы?

Оригинал статьи: Python Development in Visual Studio Code

Понравилась статья? Поделить с друзьями:
  • Visual studio code download windows 7 64 bit
  • Visual studio code c настройка windows
  • Visual studio code c как пользоваться windows
  • Visual studio c скачать бесплатно для windows 10 x64 торрент
  • Visual studio c скачать бесплатно для windows 10 x64 последняя версия