- An In Depth Tutorial on Linux Development on Windows with WSL and Visual Studio Code
- Windows: A great platform for building Linux Apps
- Install and set up WSL
- Python development
- Visual Studio Code
- Integrated Terminal
- Installing the Python extension (and additional tools)
- Debugging
- In conclusion
- More information
- приступая к работе с Visual Studio Code с подсистема Windows для Linux
- установка VS Code и расширения Remote WSL
- Обновление дистрибутива Linux
- Откройте проект WSL в Visual Studio Code
- Из командной строки
- Из VS Code
- расширения в VS Code Remote
- Установка Git (необязательно)
- Установка Терминала Windows (необязательно)
- Дополнительные ресурсы
An In Depth Tutorial on Linux Development on Windows with WSL and Visual Studio Code
In an earlier blog post, Take your Linux development experience in Windows to the next level with the Windows Subsystem for Linux (WSL) and Visual Studio Code Remote, we introduced an overview of the VS Code Remote – WSL extension, which simplifies Linux development on Windows Subsystem on Linux (WSL). Put on your SCUBA gear, because in this follow up we’ll give you a deep dive tutorial on how to setup WSL and VS Code for Python development by creating a Python “Hello World” application.
Windows: A great platform for building Linux Apps
Windows is the most popular operating system in the world, with almost 50% of developers using it every day. At the same time, many of these developers are building applications that are deployed to Linux-based servers running in the cloud or on-premises.
With WSL and VS Code, you can now seamlessly develop Linux-based applications on Windows. WSL lets you run a full Linux distro on Windows, where you can install platform-specific toolchains, utilities, and runtimes.
VS Code and the WSL extension let you develop in the context of the Linux environment, using those tools and runtimes, from the comfort of Windows. All of your VS Code settings are maintained across Windows and Linux, making it easy to switch back and forth. Commands and workspace extensions are run directly in Linux, so you don’t have to worry about pathing issues, binary compatibility, or other cross-OS challenges. You’re able to use VS Code in WSL just as you would from Windows. One tool, two operating systems.
If it sounds magical, that’s because it is! But, don’t take our word for it. Let’s get our hands dirty and build a simple Python3 application so you can experience the magic for yourself.
Install and set up WSL
You install WSL from the Microsoft Store. You can search for “Linux” in the Microsoft store to see a sub section of distributions in the store. Choose the Linux distribution you want to install and follow the prompts. You can also search for distributions in the search bar.
Select Install.
And when done, select Launch to get started. This will open a Linux terminal and complete the installation. You’ll need to create a user ID and password since we’re setting up a full Linux instance, but once that’s done, boom! You are running Linux on Windows.
Python development
If you don’t have Python already installed, run the following commands to install Python3 and pip, the package manager for Python, into your Linux installation.
And to verify, run:
This isn’t intended to be a Python tutorial, so we’ll do the canonical “Hello World” app. Create a new folder called “helloWorld” and then add a Python file that will print a message when run:
Clearly, echo isn’t a great way to do development. In a remote Linux environment (this WSL distro is technically another machine without UI, that just happens to be running locally on your computer), your development tools and experiences are pretty limited. You can run Vim in the terminal to edit your file or you can edit the sources on the Windows side through the \\wsl$ mount:
The problem with this model is that the Python runtime, pip, or any conda packages for that matter, are not installed on Windows.
Remember, Python is installed in the Linux distro, which means if we’re editing Python files on the Windows side, we can’t run or debug them unless we install the same Python development stack on Windows. And that defeats the purpose of having an isolated Linux instance set up with all our Python tools and runtimes!
What can we do? That’s where Visual Studio Code and the Remote – WSL extension comes to the rescue.
Visual Studio Code
VS Code is a lightweight, cross platform source code editor, built on open source. It comes with built-in support for modern web development with JavaScript, TypeScript, Node.js, CSS, etc. It also has a rich ecosystem of extensions (10K+) providing support for 100s of languages and frameworks, such as Python, Go, PHP, Java, C++, and C#.
If you don’t already have VS Code, download it now. It’s about 50 MB to download on Windows and sets up in less than a minute.
Now we just need the magic, and that is the Remote – WSL extension. Open the Extensions view in VS Code (Ctrl+Shift+X) and search for “wsl”. Choose the Remote – WSL extension as seen below (it should be at the top of the list) and press Install.
Once installed, head back over the WSL terminal, make sure you are in the helloWorld folder, and type in “code .” to launch VS Code (the “.” tells VS Code to open the current folder).
The first thing you’ll see is a message about “Installing VS Code Server” (the c7d83e57… number is the version of the VS Code Server that matches the client-side tools you just installed). VS Code is installing a small server on the Linux side that the desktop VS Code will then talk to.
That server will then install and host extensions in WSL, so that they run in the context of the tools and frameworks installed in WSL. In other words, your Python extension will run against the Python installed in WSL, not against what is installed on the Windows side, as it should for the proper development experience.
The next thing that happens is VS Code will start and open the helloWorld folder. You may see a quick notification telling you that VS Code is connecting to WSL, and you may be prompted to allow access to the Node.js-based server.
Now, when we hover over hello.py, we get the proper Linux path.
Integrated Terminal
If that doesn’t convince you we’re connected to the Linux subsystem, run Terminal > New Terminal (Ctrl+`) to open a new terminal instance.
You’ll start a new instance of the bash shell in WSL, again from VS Code running on Windows.
Tip: In the lower left corner of the Status Bar, you can see that we’re connected to our WSL: Ubuntu instance.
Click on it to bring up a set of Remote – WSL extension commands.
Installing the Python extension (and additional tools)
Click on hello.py to open it for editing. We are prompted with what we call an “Important” extension recommendation, in this case to install the Python extension, which will give us rich editing and debugging experiences. Go ahead and select Install and reload if prompted.
To prove that the extension is installed in WSL, open the Extensions view again (Ctrl+Shift+X). You will see a section titled WSL – Installed and you can see any extensions that are installed on the WSL side.
Upon reload, you’ll also get prompted telling you that the pylint linter is not installed. Linters are used to give us errors and warnings in our source code. Go ahead and select Install.
Now, when you edit your code, you get rich colorization and completions.
And when you save your file (Ctrl+S), you’ll get linting errors and warnings on the file.
Debugging
With our tools set up, let’s take this one step further. Set a breakpoint on line 1 of hello.py by clicking in the gutter to the left of the line number or by putting the cursor on the line and pressing F9.
Now, press F5 to run your application. You will be asked how to run the application, and since this is a simple file, just choose Python File.
The app will start, and you’ll hit the breakpoint. You can inspect variables, create watches, and navigate the call stack.
Press F10 to step and you’ll see the output of the print statement in the debug console.
You get the full development experience of Visual Studio Code, using the Linux instance installed in WSL.
If you want to open another folder in WSL, open the File menu and choose Open Folder. You’ll get a minimal file and folder navigator for the Linux file system, not the Windows file system.
If you want to switch back to the Windows, select the Show Local option and you’ll get the standard Windows File Open dialog.
In conclusion
Source
More information
With WSL, VS Code and the Remote – WSL extension, your Windows machine becomes an awesome box for developing Linux applications. Your tools run on Windows while your application runs where it will be deployed, on Linux.
Linux development is not limited to WSL. Using the Remote – SSH extension, you can develop against remote SSH hosts with the same fidelity as shown here, all from your Windows desktop.
For more information, check out the following resources:
Finally, if you really want to supercharge your Windows dev box, try out the new Windows Terminal!
This is part 2 of our 3 part series. You can find the full series here:
Craig Loewen
Program Manager II, Windows Developer Platform
Источник
приступая к работе с Visual Studio Code с подсистема Windows для Linux
Visual Studio Code, вместе с расширением Remote-WSL, позволяет использовать WSL в качестве среды разработки для полной времени непосредственно из VS Code. Вы можете выполнить следующие действия:
- Разработка в среде под управлением Linux
- Использование цепочек инструментов и служебных программ для Linux
- запускайте и отлаживать приложения Linux с помощью Windows и сохраняя доступ к средствам повышения производительности, таким как Outlook и Office
- использование встроенного терминала VS Code для запуска дистрибутива Linux по выбору
- воспользуйтесь преимуществами VS Code функций, таких как завершение кода Intellisense, linting, поддержка отладки, фрагменты кодаи модульное тестирование .
- простота управления версиями с помощью встроенной поддержки Git VS Code
- выполнение команд и VS Code расширений непосредственно в проектах WSL
- изменение файлов в Linux или смонтированной Windows файловой системе (например,/мнт/к) без беспокойства о проблемах с путями, двоичной совместимости или других трудностей между операционными системами
установка VS Code и расширения Remote WSL
перейдите на страницу установки VS Code и выберите двоичный установщик 32 или 64. установите Visual Studio Code на Windows (а не в файловую систему WSL).
При появлении запроса на Выбор дополнительных задач во время установки обязательно установите флажок Добавить в путь , чтобы можно было легко открыть папку в WSL с помощью команды Code.
Установите Пакет расширений для удаленной разработки. Этот пакет расширений включает расширение Remote-WSL в дополнение к расширениям Remote-SSH и Remote-Container, что позволяет открывать любую папку в контейнере, на удаленном компьютере или в WSL.
Чтобы установить расширение Remote-WSL, потребуется версия 1,35 или более поздняя VS Code. не рекомендуется использовать WSL в VS Code без расширения Remote-WSL, так как будет потеряна поддержка автоматического завершения, отладки, linting и т. д. Забавный факт. это расширение WSL устанавливается в $HOME/.вскоде/екстенсионс (введите команду ls $HOME\.vscode\extensions\ в PowerShell).
Обновление дистрибутива Linux
в некоторых дистрибутивах WSL Linux отсутствуют библиотеки, необходимые для запуска сервера VS Code. Вы можете добавить дополнительные библиотеки в дистрибутив Linux с помощью диспетчера пакетов.
Например, чтобы обновить Debian или Ubuntu, используйте:
Чтобы добавить wget (для получения содержимого с веб-серверов) и CA-Certificates (чтобы разрешить приложениям на основе SSL проверять подлинность SSL-соединений), введите:
Откройте проект WSL в Visual Studio Code
Из командной строки
Чтобы открыть проект из дистрибутива WSL, откройте командную строку распространения и введите: code .
Из VS Code
кроме того, можно получить доступ к дополнительным VS Code удаленным параметрам с помощью ярлыка: CTRL+SHIFT+P в VS Code, чтобы открыть палитру команд. если затем ввести, Remote-WSL вы увидите список доступных VS Code удаленных параметров, что позволит повторно открыть папку в удаленном сеансе, указать, какое распространение следует открыть в, и многое другое.
расширения в VS Code Remote
расширение Remote-WSL разделяет VS Code в архитектуру «клиент-сервер» с помощью клиента (пользовательского интерфейса), работающего на компьютере Windows, и сервера (код, Git, подключаемые модули и т. д.), запускаемые удаленно.
при запуске VS Code удаленно на вкладке «расширения» отобразится список расширений, разделенных между локальным компьютером и дистрибутивом WSL.
Установка локального расширения, например темы, должна быть установлена только один раз.
Некоторые расширения, такие как расширение Python или все, что обрабатывает такие действия, как linting или Отладка, должны устанавливаться отдельно на каждом удаленном распределении WSL. VS Code отобразит значок предупреждения ⚠ , а также зеленую кнопку «установить в WSL», если установлено локальное расширение, которое не установлено на удаленном компьютере WSL.
дополнительные сведения см. в VS Code документах:
при запуске VS Code Remote в WSL сценарии запуска оболочки запускаться не будут. Дополнительные сведения о выполнении дополнительных команд или изменении среды см. в этой статье о сценариях расширенной настройки среды .
возникли проблемы при запуске VS Code из командной строки WSL? В этом руководство по устранению неполадок содержатся советы по изменению переменных пути, устранению ошибок расширения, связанных с отсутствием зависимостей, устранению проблем с завершением строк Git, установке локального VSIX на удаленном компьютере, запуску окна браузера, порту localhost для блокировки, веб-сокеты не работают, ошибки при хранении данных расширения и многое другое.
Установка Git (необязательно)
Если вы планируете работать совместно с другими пользователями или размещать проект на сайте с открытым исходным кодом (например, GitHub), примите во внимание, что VS Code поддерживает управление версиями с помощью Git. Вкладка системы управления версиями в VS Code отслеживает все изменения и содержит общие команды Git (добавление, фиксация, принудительная отправка, извлечение) прямо в пользовательском интерфейсе.
Установка Терминала Windows (необязательно)
новая Терминал Windows включает несколько вкладок (быстро переключаться между дистрибутивами командной строки, PowerShell или несколькими установочными областями Linux), пользовательскими привязками клавиш (создайте собственные сочетания клавиш для открытия и закрытия вкладок, копирования и вставки и т. д.), эмодзи ☺ и пользовательских тем (цветовые схемы, стили и размеры шрифтов, фоновое изображение, размытие и прозрачность). дополнительные сведения см. в Терминал Windows документах.
Скачайте Терминал Windows из Microsoft Store: При установке через магазин обновления выполняются автоматически.
После установки откройте Терминал Windows и щелкните Параметры, чтобы настроить Терминал использовать файл profile.json .
Дополнительные ресурсы
К дополнительным рекомендуемым расширениям относятся следующие:
- Раскладки клавиатуры других редакторов — эти расширения позволят использовать необходимую раскладку при переходе в другой текстовый редактор (например, Atom, Sublime, Vim, eMacs, Notepad++ и т. п.).
- Расширение синхронизации параметров — позволяет синхронизировать параметры VS Code в разных установках, используя GitHub. Если вы работаете на разных компьютерах, это обеспечит согласованность среды между ними.
- Отладчик для Chrome: после завершения разработки на стороне сервера с Linux необходимо разработать и протестировать клиентскую часть. Это расширение интегрирует редактор VS Code со службой отладки браузера Chrome, что увеличивает эффективность выполнения операций.
—>
Источник