- Как настроить python для работы в Visual Studio Code
- Setting up Environments 🌲¶
- Conda Environment¶
- Installing Anaconda Distribution¶
- Creating Conda Environment¶
- Activating Conda Environment¶
- Deactivating Conda Environment¶
- Using Python Virtual Environment in VSCode
- Install Virtualenv
- Create a Virtual Environment
- VSCode Setup
- 1. Update Venv Path Settings in VSCode
- 2. Add the Virtual Environment Folder to VSCode.
Как настроить python для работы в Visual Studio Code
Несмотря на то, что python это очень простой язык программирования (*с точки зрения синтаксиса и семантики), у некоторых возникают сложности на самом первом этапе — запуска созданной программы.
В этой статье я постараюсь максимально подробно описать все шаги для этого процесса. При этом мы будем использовать один из самых популярных IDE (Integrated Development Environment или Встроенная Среда Разработчика) — Visual Studio Code (В дальнейшем VSC).
Откройте VSC и нажмите на: File -> Open Folder (Файл -> Открыть Папку)
Далее необходимо создать новый терминал для запуска ваших программ, а также создания виртуального окружения. Для этого в шапке VSC выберите: Terminal -> New Terminal (Терминал -> Новый Терминал). Либо нажмите сочетание клавиш на клавиатуре: Ctrl + Shift + ` (Тильда)
В терминале вводим операцию: py -m venv env (Если использование py выдаст вам ошибку, то попробуйте вместе этой операции использовать одну из перечисленных: python, python3)
Данная операция создаст новое виртуальное окружение и позволит нам изолировать используемые модули в нашей программе.
Далее активируем виртуальное окружение: env\Scripts\activate
Тут важно использовать именно обратные слэши для операционной системы Windows. На Mac OS операция будет выглядеть следующим образом: source env/bin/activate
Если вы сделали все правильно, то увидите префикс (env) в консоли.
Setting up Environments 🌲¶
The main purpose of using environments is to create a segregation between the dependencies of different python projects. It eliminates (at least tries to) dependency conflicts since each project has it’s own set of dependencies, isolated from one another.
Suppose you are working on two projects, Project_1 and Project_2 , both of which have a dependency on the same library, let’s say the awesome Requests library. Dependency conflict will arise, if for some reason, the two projects need different versions of Request library. For example, maybe Project_1 needs v1.0.0 , while Project_2 requires the newer v2.0.0 .
This can easily be avoided by using individual environment for each project where all the dependencies of the corresponding project will reside. There are multiple ways you can create environment. We’ll mainly focus on creating python3 based conda environment and native virtual environment .
Conda Environment¶
Installing Anaconda Distribution¶
Install anaconda on your machine. I personally prefer miniconda over the full fledged anaconda. The installation guide can be found here:
Creating Conda Environment¶
After installing anaconda, to create a python3 environment with a specific version of python, type the following command. This will create an environemnt named myenv with python 3.7:
$ conda create -n myenv python=3.7
Activating Conda Environment¶
After creating the conda environment, type the folling command to activate the myenv environment:
Deactivating Conda Environment¶
To deactivate, simply type:
Using Python Virtual Environment in VSCode
When trying to use a Python virtual environment in VSCode, it was not detecting the virtual environment. The solution was very simple, but I couldn’t find it on Google.
Most of the solutions found on StackOverflow and Github were suggesting to change the pythonPath in VSCode settings.
This article shows how to use a Python virtual environment in VSCode, without having to change the pythonPath in VSCode settings.
Just for the sake of completeness, we will start by installing virtualenv and creating a virtual environment. If you are only interested in the VSCode setup, skip to the VSCode setup section directly.
Install Virtualenv
We will be using virtualenv to create our python virtual environments. We will use pip to install it.
Install virtualenv using pip:
Create a Virtual Environment
First, let us create a folder .virtualenvs in the home directory. This is where we will keep all our virtual environments.
cd ~ mkdir .virtualenvs cd .virtualenvs
From inside the .virtualenvs directory, create a new virtual environment using virtualenv
Now, let us activate the virtual environment
We will install a package in the virtual environment so that we can test if the setup is working as expected.
We will create test.py that will import from the excel package that we just installed.
from excel import OpenExcel
VSCode Setup
At first, if you open the test.py file, assuming you have Python linter extension installed, VSCode will show an error like this.
This is because VSCode is not using the correct python interpreter. There are two ways in which you can fix this.
1. Update Venv Path Settings in VSCode
Open VSCode preferences ( Ctrl + , ) and search for “venv”. Add ~/.virtualenvs to the “Venv Path” settings, like so:
Restart VSCode and click on the interpreter version on the left-bottom corner.
Now, you will be able to see the virtual environment python interpreter in the interpreter list. Select it, now the issue should be resolved.
2. Add the Virtual Environment Folder to VSCode.
Add the folder that contains the virtual environment to VSCode, in our case, it is the ~/.virtualenv folder. Once added, you will be able to select the interpreter by clicking on the interpreter version displayed on the left-bottom corner.
Programmer | Tech Blogger | Multitasker | Learner Forever | Someone who believes knowledge grows by sharing | Looking forward to using spare time productively