Как активировать виртуальное окружение в pycharm

от admin

Configure a virtual environment

PyCharm makes it possible to use the virtualenv tool to create a project-specific isolated virtual environment . The main purpose of virtual environments is to manage settings and dependencies of a particular project regardless of other Python projects. virtualenv tool comes bundled with PyCharm, so the user doesn’t need to install it.

For Python 3.3+ the built-in venv module is used, instead of the third-party virtualenv utility.

Create a virtualenv environment

Do one of the following:

Click the Python Interpreter selector and choose Add New Interpreter .

Press Ctrl+Alt+S to open Settings and go to Project: <project name> | Python Interpreter . Click the Add Interpreter link next to the list of the available interpreters.

Click the Python Interpreter selector and choose Interpreter Settings . Click the Add Interpreter link next to the list of the available interpreters.

Select Add Local Interpreter .

In the left-hand pane of the Add Python Interpreter dialog, select Virtualenv Environment .

The following actions depend on whether you want to create a new virtual environment or to use an existing one.

Specify the location of the new virtual environment in the Location field, or click and browse for the desired location in your file system. The directory for the new virtual environment should be empty.

Choose the base interpreter

Choose the base interpreter from the list, or click and find the desired Python executable in your file system.

Select the Inherit global site-packages checkbox if you want all packages installed in the global Python on your machine to be added to the virtual environment you’re going to create. This checkbox corresponds to the —system-site-packages option of the virtualenv tool.

Choose the desired interpreter from the list.

If the desired interpreter is not on the list, click , and then browse for the desired Python executable (for example, venv/bin/python on macOS or venv\Scripts\python.exe on Windows).

The selected virtual environment will be reused for the current project.

Click OK to complete the task.

If PyCharm displays the Invalid environment warning, it means that the specified Python binary cannot be found in the file system, or the Python version is not supported. Check the Python path and install a new version, if needed.

You can create as many virtual environments as required. To easily tell them from each other, use different names.

Use an existing interpreter

Press Ctrl+Alt+S to open the IDE settings and select Project <project name> | Python Interpreter .

Show all available interpreters

Expand the list of the available interpreters and click the Show All link. Alternatively, click the icon and select Show All .

Virtual environments are marked with .

Select the target environment from the list and click OK to confirm your choice.

PyCharm can create a virtual environment for your project based on the project requirements.

Create a virtual environment using the project requirements

Open any directory with your source files that contains the requirements.txt or setup.py file: select File | Open from the main menu and choose the directory.

If no virtual environment has been created for this project, PyCharm suggests creating it:

Keep the suggested options, or specify the environment location or base Python interpreter. Click OK to complete the task.

The environment is created

Once you click OK , PyCharm creates an environment and installs all the required packages. On the completion, see the notification popup:

Warning with options for configuring a project interpreter

Note that if you ignore a suggestion to create a virtual environment, PyCharm won’t create a Python interperter for your project. So, any time when you open a .py file, you’ll see the warning with the options for configuring a project interpreter:

This approach is particularly helpful when you want to upgrade a version of Python your environment is based on, for example, from 3.5 to 3.9. You can specify a new base interpreter and use requirements.txt to ensure all the needed packages are installed.

For any of the configured Python interpreters (but Docker-based), you can:

Once you have create a new virtual environment, you can reuse it for your other projects. Learn more how to setup an existing environment as a Python interpreter.

Configure PyCharm With the Python Virtual Environment

It will show you how to configure PyCharm to work with Python in a virtual environment. Also you will configure the requirements.txt.

Start PyCharm create a new project or clone it from your repository. As an example I created a file first_example.py to write inside the main. I specify that this is only an example and for reasons of brevity does not follow the structure of a Python project.

Install Python

First, make sure Python 3 is installed by running the following command:

If python 2 and 3 is installed, the output will be the installed version of python 2 and 3.

If python is not installed, run the command and choose version 3.6 for example¹:

Create virtualenv with:

It is possible to create virtualenv on the same directory or on a different directory. In this article I use the same directory as the project directory. In my case i call the directory “venv”, but we can use “any_name”:

If all went well you will have the folder venv in your project:

To activate virtual environment lunch:

The fact that there is venv in parenthesis means that all libraries will be installed in the virtual environment and will not “dirty” the global environment. For more information about the virtual environment read this https://docs.python.org/3/tutorial/venv.html.

Python Interpreter

If you can’t find the python interpreter in the previous window then you have to create or add it. Just go to File →Settings →Project →Python interpreter →Add.

In the Interpreter box is present the path of our virtual environment:

Click Ok and then on Apply, then we will see all the libraries installed in our virtual environment.

Executing a program in the virtual environment

Let’s consider the example first_example, go to Add Configuration…

A window will open. Click on the “+” in the upper left corner. Now we can configure our Python program ready to run. Enter the “Name” (first_example), set “Script path” to the file where the main is located. Then we should find the “Python interpreter” already configured, in any case, having added it we will find it in the dropdown menu. Note that the interpreter path is the one related to the virtual environment created!

Lunch simple program

Let’s consider the following code:

requirements.txt

If you share a project with other users using a build system or plan to copy the project to another location where an environment is to be restored, you must specify the external packages required by the project. The recommended approach is to use a requirements.txt file, which contains a list of pip commands and allows you to install the required versions of dependent packages.

We assume to install Pandas (data analysis and manipulation tool), we lunch:

Введение в Virtual Environments

Если вы работали с несколькими проектами, в которых использовался Python, то наверняка вы встречались с проблемой поломки одного из проекта, потому что обновленная версия библиотеки для другого проекта, не применима для текущего. Т.е. если вы работаете с Python и не используете miniconda или anaconda, то установка и обновление библиотек python постоянно ломает ваши проекты. Эта проблема называется «Ад зависимостей».

Читать:
Как перебирать словарь в цикле python

Поэтому лучшим подходом будет создавать для каждого отдельного проекта свою среду. В этой статье будет рассмотрена библиотека venv для настройки Virtual Environment для Windows.

Виртуальная среда — это способ Python для разделения зависимостей между проектами.

Создание виртуальной среды — venv в Windows

venv -это пакет, поставляемый с Python 3.

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

Чтобы создать виртуальную среду, перейдите в каталог вашего проекта и запустите venv.

venv создаст виртуальную установку Python в директории venv .

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

Активация и деактивация виртуальной среды Python

Далее необходимо активировать виртуальную среду.

Для этого необходимо в консоли cmd запустить .\venv\Scripts\activate или файл .\venv\Scripts\activate.bat , или .\venv\Scripts\Activate.ps1 .

Префикс вашего рабочего каталога изменится (выделил желтым — venv)

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

Установка пакетов в виртуальную среду

Пример:

pip позволяет вам указать, какую версию пакета установить, используя спецификаторы версии . Например, чтобы установить определенную версию requests :

Как сохранить пакеты в файл requirements.txt

Pip может экспортировать список всех установленных пакетов и их версий с помощью freeze команды: pip freeze > requirements.txt .

Будет выведен список спецификаторов пакетов, таких как:

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

Установить пакеты из файла requirements.txt

Как запустить скрипт Python в виртуальной среде. Пример автоматизации с помощью cmd

Для того, чтобы запустить скрипт, достаточно внутри директории с проектом (со средой) запустить команду:

Либо создать файл cmd с содержимым и запустить его:

Создание виртуальной среды с помощью PyCharm

Для более легкой работы с виртуальными средами на Windows рекомендую установить PyCharm (Community Edition бесплатная). При создании проекта он сам создаст виртуальную среду и будет запускать файл в этой виртуальной среде:

Новую виртуальную среду можно создать с помощью разных инструментов в Pycharm:

virtualenv Python

virtualenv это инструмент для изоляции проектов друг от друга.

Можно создавать проекты с разными установленными пакетами, разными версиями Python, Pip и так далее.

Применяется чаще всего с двумя целями:

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

Вторая: не «портить» установленный системный Python, превращая его в кашу из кучи разных пакетов.

Если вам нужно настроить virtualenv на хостинге — инструкция Beget

Чтобы проверить установлен virtualenv или нет выполните

Если в результате вы видите что-то похожее, то можно продолжать. Ваша версия может отличаться от 20.0.21 это нормально.

virtualenv 20.0.21 from c:\users\andrei\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv\__init__.py

Если в результате вы получили сообщение о том что команда неизвестна — прочитайте статью «Установка virtualenv в Windows и Linux

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

Создадим директорию, в которой будем хранить виртуальные окружения.

mkdir virtualenvs
cd virtualenvs

Создадим новое виртуальное окружение, которое назовём test_env

Или, если мы хотим явно указать, что нужно создать виртуальное окружение именно для Python3.

virtualenv -p python3 test_env

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

created virtual environment CPython3.8.2.final.0-32 in 1410ms creator CPython3Windows(dest=C:\Users\Andrei\virtualenvs\test_env, clear=False, global=False) seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, via=copy, app_data_dir=C:\Users\Andrei\AppData\Local\pypa\virtualenv\seed-app-data\v1.0.1) activators BashActivator,BatchActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

Выбор версии Python для окружения

Чтобы создать окружение с определённой версией Python используйте команду с указанием версии.

Чтобы это сработало нужно иметь установленный Python данной версии

virtualenv —python=/usr/bin/python3.6 python36

Из чего состоит окружение

Зайдём внутрь test_env и посмотрим, что там находится

cd test_env
dir

Mode LastWriteTime Length Name —- ————- —— —- d—— 6/5/2020 9:35 PM Lib d—— 6/5/2020 9:35 PM Scripts -a—- 6/5/2020 9:35 PM 42 .gitignore -a—- 6/5/2020 9:35 PM 421 pyvenv.cfg

cd test_env
dir

Директория Scripts в Linux будет называться bin.

Перейдём туда и изучим состав.

Mode LastWriteTime Length Name —- ————- —— —- -a—- 6/5/2020 9:35 PM 2313 activate -a—- 6/5/2020 9:35 PM 1069 activate.bat -a—- 6/5/2020 9:35 PM 3179 activate.fish -a—- 6/5/2020 9:35 PM 1815 activate.ps1 -a—- 6/5/2020 9:35 PM 1216 activate.xsh -a—- 6/5/2020 9:35 PM 1225 activate_this.py -a—- 6/5/2020 9:35 PM 529 deactivate.bat -a—- 6/5/2020 9:35 PM 97159 easy_install-3.8.exe -a—- 6/5/2020 9:35 PM 97159 easy_install.exe -a—- 6/5/2020 9:35 PM 97159 easy_install3.exe -a—l 6/5/2020 9:35 PM 0 libcrypto-1_1.dll -a—l 6/5/2020 9:35 PM 0 libffi-7.dll -a—l 6/5/2020 9:35 PM 0 libssl-1_1.dll -a—- 6/5/2020 9:35 PM 97150 pip-3.8.exe -a—- 6/5/2020 9:35 PM 97150 pip.exe -a—- 6/5/2020 9:35 PM 97150 pip3.8.exe -a—- 6/5/2020 9:35 PM 97150 pip3.exe -a—- 6/5/2020 9:35 PM 25 pydoc.bat -a—l 6/5/2020 9:35 PM 0 pyexpat.pyd -a—l 6/5/2020 9:35 PM 0 python.exe -a—l 6/5/2020 9:35 PM 0 python3.dll -a—l 6/5/2020 9:35 PM 0 python38.dll -a—l 6/5/2020 9:35 PM 0 pythonw.exe -a—l 6/5/2020 9:35 PM 0 select.pyd -a—l 6/5/2020 9:35 PM 0 sqlite3.dll -a—l 6/5/2020 9:35 PM 0 tcl86t.dll -a—l 6/5/2020 9:35 PM 0 tk86t.dll -a—l 6/5/2020 9:35 PM 0 unicodedata.pyd -a—l 6/5/2020 9:35 PM 0 vcruntime140.dll -a—- 6/5/2020 9:35 PM 97137 wheel-3.8.exe -a—- 6/5/2020 9:35 PM 97137 wheel.exe -a—- 6/5/2020 9:35 PM 97137 wheel3.exe -a—l 6/5/2020 9:35 PM 0 winsound.pyd -a—l 6/5/2020 9:35 PM 0 _asyncio.pyd -a—l 6/5/2020 9:35 PM 0 _bz2.pyd -a—l 6/5/2020 9:35 PM 0 _ctypes.pyd -a—l 6/5/2020 9:35 PM 0 _ctypes_test.pyd -a—l 6/5/2020 9:35 PM 0 _decimal.pyd -a—l 6/5/2020 9:35 PM 0 _elementtree.pyd -a—l 6/5/2020 9:35 PM 0 _hashlib.pyd -a—l 6/5/2020 9:35 PM 0 _lzma.pyd -a—l 6/5/2020 9:35 PM 0 _msi.pyd -a—l 6/5/2020 9:35 PM 0 _multiprocessing.pyd -a—l 6/5/2020 9:35 PM 0 _overlapped.pyd -a—l 6/5/2020 9:35 PM 0 _queue.pyd -a—l 6/5/2020 9:35 PM 0 _socket.pyd -a—l 6/5/2020 9:35 PM 0 _sqlite3.pyd -a—l 6/5/2020 9:35 PM 0 _ssl.pyd -a—l 6/5/2020 9:35 PM 0 _testbuffer.pyd -a—l 6/5/2020 9:35 PM 0 _testcapi.pyd -a—l 6/5/2020 9:35 PM 0 _testconsole.pyd -a—l 6/5/2020 9:35 PM 0 _testimportmultiple.pyd -a—l 6/5/2020 9:35 PM 0 _testmultiphase.pyd -a—l 6/5/2020 9:35 PM 0 _tkinter.pyd

Обратим внимание на скрипты activate, activate.bat и activate.ps1 один из них нам понадобится, а какой — зависит от Вашего окружения.

Под Linux нужен будет activate

Под Windows activate.bat для обычной командной строки или activate.ps1 для PowerShell. не все пакеты работают одинаково, некоторые не поддерживают PowerShell, но какие-то действия проще делать в нём.

Виртуальные окружения в PyCharm

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

Это делается на этапе создания проекта

Выбор виртуального окружения при создании проекта в PyCharm www.andreyolegovich.ru

По умолчанию доступны virtualenv, pipenv и conda

Выбор виртуального окружения при создании проекта в PyCharm www.andreyolegovich.ru

Название для окружения задаётся здесь:

Выбор виртуального окружения при создании проекта в PyCharm www.andreyolegovich.ru

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

Выбор виртуального окружения при создании проекта в PyCharm www.andreyolegovich.ru

Подпишитесь на Telegram канал @aofeed чтобы следить за выходом новых статей и обновлением старых

Похожие статьи