Vs code для python linux

Содержание
  1. Visual Studio Code on Linux
  2. Installation
  3. Debian and Ubuntu based distributions
  4. RHEL, Fedora, and CentOS based distributions
  5. openSUSE and SLE-based distributions
  6. AUR package for Arch Linux
  7. Nix package for NixOS (or any Linux distribution using Nix package manager)
  8. Installing .rpm package manually
  9. Updates
  10. Node.js
  11. Setting VS Code as the default text editor
  12. xdg-open
  13. Debian alternatives system
  14. Windows as a Linux developer machine
  15. Windows Subsystem for Linux
  16. Next steps
  17. Common questions
  18. Azure VM Issues
  19. Debian and moving files to trash
  20. Conflicts with VS Code packages from other repositories
  21. «Visual Studio Code is unable to watch for file changes in this large workspace» (error ENOSPC)
  22. I can’t see Chinese characters in Ubuntu
  23. Package git is not installed
  24. The code bin command does not bring the window to the foreground on Ubuntu
  25. Cannot install .deb package due to «/etc/apt/sources.list.d/vscode.list: No such file or directory»
  26. Cannot move or resize the window while X forwarding a remote window
  27. Using the custom title bar
  28. Broken cursor in editor with display scaling enabled
  29. Repository changed its origin value
  30. Visual Studio Code – редактор кода для Python
  31. Что такое Visual Studio Code
  32. Установка
  33. Windows
  34. Linux
  35. MacOS
  36. Настройка для Python: полезные плагины
  37. Python (от Microsoft)
  38. autoDocstring (автор Nils Werner)
  39. Code Runner (автор Jun Han)
  40. Trailing Spaces by Shardul Mahadik (автор Shardul Mahadik)
  41. Better Comments (автор Aaron Bond)
  42. Djaneiro (автор Scott Barkman)
  43. flask-snippets (автор cstrap)
  44. Code Linting
  45. Запуск кода
  46. Стандартный запуск кода
  47. Запуск кода с Code Runner
  48. Работа с проектом
  49. Тестирование
  50. Отладка
  51. Интеграция с Git
  52. Работа с виртуальной средой (virtualenv)
  53. Заключение

Visual Studio Code on Linux

Installation

See the Download Visual Studio Code page for a complete list of available installation options.

By downloading and using Visual Studio Code, you agree to the license terms and privacy statement.

Debian and Ubuntu based distributions

The easiest way to install Visual Studio Code for Debian/Ubuntu based distributions is to download and install the .deb package (64-bit), either through the graphical software center if it’s available, or through the command line with:

Note that other binaries are also available on the VS Code download page.

Installing the .deb package will automatically install the apt repository and signing key to enable auto-updating using the system’s package manager. Alternatively, the repository and key can also be installed manually with the following script:

Then update the package cache and install the package using:

RHEL, Fedora, and CentOS based distributions

We currently ship the stable 64-bit VS Code in a yum repository, the following script will install the key and repository:

Then update the package cache and install the package using dnf (Fedora 22 and above):

Or on older versions using yum :

Due to the manual signing process and the system we use to publish, the yum repo may lag behind and not get the latest version of VS Code immediately.

Visual Studio Code is officially distributed as a Snap package in the Snap Store:

You can install it by running:

Once installed, the Snap daemon will take care of automatically updating VS Code in the background. You will get an in-product update notification whenever a new update is available.

Note: If snap isn’t available in your Linux distribution, please check the following Installing snapd guide, which can help you get that set up.

Learn more about snaps from the official Snap Documentation.

openSUSE and SLE-based distributions

The yum repository above also works for openSUSE and SLE-based systems, the following script will install the key and repository:

Then update the package cache and install the package using:

AUR package for Arch Linux

To get more information about the installation from the AUR, please consult the following wiki entry: Install AUR Packages.

Nix package for NixOS (or any Linux distribution using Nix package manager)

There is a community maintained VS Code Nix package in the nixpkgs repository. In order to install it using Nix, set allowUnfree option to true in your config.nix and execute:

Installing .rpm package manually

The VS Code .rpm package (64-bit) can also be manually downloaded and installed, however, auto-updating won’t work unless the repository above is installed. Once downloaded it can be installed using your package manager, for example with dnf :

Note that other binaries are also available on the VS Code download page.

Updates

VS Code ships monthly and you can see when a new release is available by checking the release notes. If the VS Code repository was installed correctly, then your system package manager should handle auto-updating in the same way as other packages on the system.

Note: Updates are automatic and run in the background for the Snap package.

Node.js

Node.js is a popular platform and runtime for easily building and running JavaScript applications. It also includes npm, a Package Manager for Node.js modules. You’ll see Node.js and npm mentioned frequently in our documentation and some optional VS Code tooling requires Node.js (for example, the VS Code extension generator).

If you’d like to install Node.js on Linux, see Installing Node.js via package manager to find the Node.js package and installation instructions tailored to your Linux distribution. You can also install and support multiple versions of Node.js by using the Node Version Manager.

Читайте также:  What is open source code in linux

To learn more about JavaScript and Node.js, see our Node.js tutorial, where you’ll learn about running and debugging Node.js applications with VS Code.

Setting VS Code as the default text editor

xdg-open

You can set the default text editor for text files ( text/plain ) that is used by xdg-open with the following command:

Debian alternatives system

Debian-based distributions allow setting a default editor using the Debian alternatives system, without concern for the MIME type. You can set this by running the following and selecting code:

If Visual Studio Code doesn’t show up as an alternative to editor , you need to register it:

Windows as a Linux developer machine

Another option for Linux development with VS Code is to use a Windows machine with the Windows Subsystem for Linux (WSL).

Windows Subsystem for Linux

With WSL, you can install and run Linux distributions on Windows. This enables you to develop and test your source code on Linux while still working locally on a Windows machine. WSL supports Linux distributions such as Ubuntu, Debian, SUSE, and Alpine available from the Microsoft Store.

When coupled with the Remote — WSL extension, you get full VS Code editing and debugging support while running in the context of a Linux distro on WSL.

See the Developing in WSL documentation to learn more or try the Working in WSL introductory tutorial.

Next steps

Once you have installed VS Code, these topics will help you learn more about it:

  • Additional Components — Learn how to install Git, Node.js, TypeScript, and tools like Yeoman.
  • User Interface — A quick orientation to VS Code.
  • User/Workspace Settings — Learn how to configure VS Code to your preferences through settings.

Common questions

Azure VM Issues

I’m getting a «Running without the SUID sandbox» error?

You can safely ignore this error.

Debian and moving files to trash

If you see an error when deleting files from the VS Code Explorer on the Debian operating system, it might be because the trash implementation that VS Code is using is not there.

Run these commands to solve this issue:

Conflicts with VS Code packages from other repositories

Some distributions, for example Pop!_OS provide their own code package. To ensure the official VS Code repository is used, create a file named /etc/apt/preferences.d/code with the following content:

«Visual Studio Code is unable to watch for file changes in this large workspace» (error ENOSPC)

When you see this notification, it indicates that the VS Code file watcher is running out of handles because the workspace is large and contains many files. Before adjusting platform limits, make sure that potentially large folders, such as Python .venv , are added to the files.watcherExclude setting (more details below). The current limit can be viewed by running:

The limit can be increased to its maximum by editing /etc/sysctl.conf (except on Arch Linux, read below) and adding this line to the end of the file:

The new value can then be loaded in by running sudo sysctl -p .

While 524,288 is the maximum number of files that can be watched, if you’re in an environment that is particularly memory constrained, you may want to lower the number. Each file watch takes up 1080 bytes, so assuming that all 524,288 watches are consumed, that results in an upper bound of around 540 MiB.

Arch-based distros (including Manjaro) require you to change a different file; follow these steps instead.

Another option is to exclude specific workspace directories from the VS Code file watcher with the files.watcherExclude setting. The default for files.watcherExclude excludes node_modules and some folders under .git , but you can add other directories that you don’t want VS Code to track.

I can’t see Chinese characters in Ubuntu

We’re working on a fix. In the meantime, open the application menu, then choose File > Preferences > Settings. In the Text Editor > Font section, set «Font Family» to Droid Sans Mono, Droid Sans Fallback . If you’d rather edit the settings.json file directly, set editor.fontFamily as shown:

Package git is not installed

This error can appear during installation and is typically caused by the package manager’s lists being out of date. Try updating them and installing again:

The code bin command does not bring the window to the foreground on Ubuntu

Running code . on Ubuntu when VS Code is already open in the current directory will not bring VS Code into the foreground. This is a feature of the OS which can be disabled using ccsm .

Under General > General Options > Focus & Raise Behaviour, set «Focus Prevention Level» to «Off». Remember this is an OS-level setting that will apply to all applications, not just VS Code.

Cannot install .deb package due to «/etc/apt/sources.list.d/vscode.list: No such file or directory»

This can happen when sources.list.d doesn’t exist or you don’t have access to create the file. To fix this, try manually creating the folder and an empty vscode.list file:

Читайте также:  Linux или mac 2012

Cannot move or resize the window while X forwarding a remote window

If you are using X forwarding to use VS Code remotely, you will need to use the native title bar to ensure you can properly manipulate the window. You can switch to using it by setting window.titleBarStyle to native .

Using the custom title bar

The custom title bar and menus were enabled by default on Linux for several months. The custom title bar has been a success on Windows, but the customer response on Linux suggests otherwise. Based on feedback, we have decided to make this setting opt-in on Linux and leave the native title bar as the default.

The custom title bar provides many benefits including great theming support and better accessibility through keyboard navigation and screen readers. Unfortunately, these benefits do not translate as well to the Linux platform. Linux has a variety of desktop environments and window managers that can make the VS Code theming look foreign to users. For users needing the accessibility improvements, we recommend enabling the custom title bar when running in accessibility mode using a screen reader. You can still manually set the title bar with the Window: Title Bar Style ( window.titleBarStyle ) setting.

Broken cursor in editor with display scaling enabled

Due to an upstream issue #14787 with Electron, the mouse cursor may render incorrectly with scaling enabled. If you notice that the usual text cursor is not being rendered inside the editor as you would expect, try falling back to the native menu bar by configuring the setting window.titleBarStyle to native .

Repository changed its origin value

If you receive an error similar to the following:

Use apt instead of apt-get and you will be prompted to accept the origin change:

Источник

Visual Studio Code – редактор кода для Python

Для написания реального проекта на Python не подойдет обычный текстовый редактор или стандартная IDLE. Чтобы упростить процесс написания кода, избежать глупых ошибок и получить все необходимые инструменты в одной «коробке», программисты используют специальные редакторы кода или профессиональные IDE.

Что такое Visual Studio Code

VS Code – это редактор кода, который поддерживает большинство популярных языков программирования. К его преимуществам можно отнести:

  • Открытый исходный код.
  • Большое количество плагинов.
  • Небольшой размер и низкие требования к ресурсам компьютера.
  • Поддержка большинства операционных систем.
  • Автоматическое использование conda и виртуальных сред.
  • Редактирование кода в Jupyter.

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

Установка

VS Code — кроссплатформенное приложение, его можно установить на любую популярную операционную систему.

Windows

Для установки на Windows необходимо:

  1. Скачать установщик с официального сайта.
  2. Запустить программу установки и следовать инструкциям.
  3. Убедиться, что приложение доступно для использования. По умолчанию устанавливается в «…AppData\Local\Programs\Microsoft VS Code».

Linux

Зачастую VS Code есть в репозиториях. В этом случае достаточно выполнить команду в терминале: « sudo apt install vscode «.

Также возможен и следующий вариант установки:

  1. Скачать .deb файл с официального сайта.
  2. Запустить терминал из того каталога, в котором находится файл (или использовать команду «cd»).
  3. Выполнить команду: « sudo apt install .deb «, где — имя скачанного файла.

MacOS

Для установки на MacOS нужно:

  1. Скачать установщик для MacOS с официального сайта.
  2. Дважды щёлкнуть на архив, чтобы открыть его содержимое.
  3. Перетащить «Visual Studio Code.app» в приложения (Applications), чтобы сделать иконку доступной из панели запуска.
  4. Добавить VS Code в Dock, для этого кликнуть правой кнопкой мыши по значку и выбрать в контекстном меню «Параметры» — «Сохранить в Dock».

Настройка для Python: полезные плагины

Для установки плагина необходимо:

  1. Нажать на значок кубиков на левой панели — пункт «Extensions».
  2. Ввести в поле поиска название необходимого расширения.
  3. Открыть страницу расширения, для этого нажать на найденный результат.
  4. Прочитать информацию о расширении и нажать зеленую кнопку «Install».

На экране выше выбрано установленное расширение. Его можно удалить (Uninstall) или отключить не удаляя (Disable).

Python (от Microsoft)

Расширение «Python» от компании Microsoft – это первое и главное расширения для программиста на Python.

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

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

autoDocstring (автор Nils Werner)

Плагин позволяет быстро создавать документацию для функций. Доступно несколько форматов документации: стандартная, Google, NumPy и другие.

Писать документацию для функций очень важно, потому что с её помощью другие программисты понимают, что делает функция и зачем она нужна. Для крупного проекта пишется огромный объем документации, расширение autoDocstring значительно упрощает этот процесс и экономит время программистов.

Code Runner (автор Jun Han)

Название расширения полностью описывает его назначение. С его помощью можно выполнять код (не только на языке Python) и выводить результаты в специальное встроенное окно.

Расширение позволяет не переключаться между редактором и терминалом, потому что результаты выводятся в специальное встроенное окно «OUTPUT».

Trailing Spaces by Shardul Mahadik (автор Shardul Mahadik)

Правильность работы кода на Python напрямую зависит от отступов, которые определяют вложенность блоков кода. Неправильные отступы (лишний пробел, сочетание пробелов и табуляций) часто приводят к ошибкам, плагин решает эту проблему. Он подсвечивает завершающие пробелы и позволяет удалить их одним кликом.

Читайте также:  Автозапуск модуля ядра linux

Better Comments (автор Aaron Bond)

Плагин позволяет создавать более продвинутые комментарии, которые подсвечиваются разными цветами в зависимости от их типа:

  • Предупреждение.
  • Вопрос.
  • «TODO» — сделать что-то.
  • Особенности.

Djaneiro (автор Scott Barkman)

Коллекция сниппетов (фрагментов кода) для шаблонов, моделей и форм Django. Импортирован в VS Code из текстового редактора Sublime Text.

flask-snippets (автор cstrap)

Аналогично Djaneiro плагин импортирован из других редакторов, он позволяет использовать большое количество сниппетов для фрейморка Flask.

Code Linting

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

Для того чтобы включить Linting в VS Code, его нужно установить через менеджер пакетов: « pip install pylint »

Запуск кода

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

Стандартный запуск кода

Необходимо нажать в любое место файла правой кнопкой мыши и выбрать в контекстном меню пункт «Run Python File In Terminal» (можно воспользоваться зеленой кнопкой воспроизведения в правом верхнем углу).

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

Запуск кода с Code Runner

Если в VS Code добавлено расширение Code Runner, то запустить код можно:

  • Нажав на кнопку «Run Code» в правом верхнем углу (которая заменит там кнопку стандартного запуска).
  • Открыв контекстное меню правой кнопкой мыши на файле, который следует запустить и выбрав пункт «Run Code».
  • Использовав сочетания клавиш «Ctrl+Alt+N».

В отличии от стандартного метода, Code Runner выводит результаты в специальное окно Output, а не в терминал. Кроме того, он также отображает информацию о коде ошибки и времени выполнения скрипта.

Работа с проектом

VS Code позволяет работать с большим количеством файлов и папок, в нём легко создавать, удалять и систематизировать их. Помимо этого, в редакторе кода реализованы такие вещи, как тестирование, отладка и интеграция с Git.

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

VS Code способен автоматически распознавать тесты, написанные с помощью unittest, pytest или Nose фреймворков.

Для того чтобы запустить существующий тест, необходимо открыть его в редакторе, нажать правой кнопкой мыши в любом месте файла и выбрать пункт «Run Current Test File». Программа предложит определить структуру и местоположение тестов в проекте, а также создать шаблон для тестов. Все указанные данные сохраняются в настройках рабочего пространства, в файле settings.json.

Тесты, входящие в проект, можно найти, нажав на нижний значок в нижнем меню (химический сосуд). Оттуда же с помощью зеленой двойной кнопки «плей» можно запустить все тесты.

Отладка

VS Code поддерживает все необходимые функции отладки кода:

  • Автоматическое отслеживание переменных.
  • Просмотр выражений.
  • Точки останова.
  • Контроль стека вызова.

Для запуска режима отладки нужно нажать клавишу «F5» или использовать одно из меню (в верхней или левой части экрана). После чего появится возможность выбрать объект отладки:

  • Скрипт.
  • Модуль.
  • Веб-приложение django.
  • Веб-приложение flask и т. д.

Программист может поставить точки останова, приостановить отладку и «шагать» по коду. В левой части экрана появляются такие важные меню, как переменные, просмотр, стек вызова и точки останова.

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

VS Code имеет встроенную поддержку таких систем контроля версий, как Git и GitHub. Кроме того, с помощью плагинов программист может добавить поддержку и других систем, которые можно совместно использовать.

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

Для использования функций Git нужно открыть папку с проектом. После этого в боковом меню выбрать кнопку «Source Control». В нём выбираем «Initialize Repjsitory».

Тогда можно делать следующее:

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

Работа с виртуальной средой (virtualenv)

Виртуальная среда — это контекст (набор зависимостей) в котором выполняется проект. Любая среда прежде всего состоит из интерпретатора и некоторого количества установленных пакетов.

VS Code позволяет много полезных функций для работы с различными средами. По умолчанию Python использует интерпретатор по пути, находящемуся в системной переменной. Если нужно использовать конкретную среду, необходимо открыть палитру команд, нажав сочетание клавиш «Ctrl+Shift+P». Затем ввести туда команду «Python: Select Interpreter».

Также это можно сделать нажав внизу экрана на указанный там текущий интерпретатор. Вы также попадёте в меню выбора и при необходимости можете добавить новый из виртуальной среды.

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

Заключение

VS Code – это легкий редактор кода, который может похвастаться мощным функционалом для написания кода на Python. Он подойдет не только для написания скриптов, но и для создания серьезных проектов.

С помощью различных плагинов VS Code можно приспособить для выполнения любых задач на Python или любом другом языке.

Источник

Оцените статью