Failed to create virtual environment pycharm ubuntu что делать
Создание виртуальных окружений и установка библиотек для Python 3 в IDE PyCharm
Язык программирования Python считается достаточно простым. На нем легче и быстрее пишутся программы, по сравнению с компилируемыми языками программирования. Для Python существует множество библиотек, позволяющих решать практически любые задачи. Есть, конечно, и минусы и другие нюансы, но это отдельная тема.
Довольно часто я вижу, как мои знакомые и друзья начинают изучать Python и сталкиваются с проблемой установки и использования сторонних библиотек. Они могут несколько часов потратить на установку библиотеки, и даже, могут не справиться с этим и забить на неё. В то время как, в большинстве случаев, это можно было сделать за несколько минут.
Статья начинается с базовых вещей: с установки Python 3, инструментов разработки Pip и Virtualenv и среды разработки PyCharm в Windows и в Ubuntu. Для многих это не представляет трудностей и возможно, что уже всё установлено.
После чего будет то, ради чего задумывалась статья, я покажу как в PyCharm создавать и использовать виртуальные окружения и устанавливать в них библиотеки с помощью Pip.
Установка Python и Pip
Pip является менеджером пакетов для Python. Именно с помощью него обычно устанавливаются модули/библиотеки для разработки в виде пакетов. В Windows Pip можно установить через стандартный установщик Python. В Ubuntu Pip ставится отдельно.
Установка Python и Pip в Windows
Для windows заходим на официальную страницу загрузки, где затем переходим на страницу загрузки определенной версии Python. У меня используется Python 3.6.8, из-за того, что LLVM 9 требует установленного Python 3.6.
Во время установки ставим галочку возле Add Python 3.x to PATH и нажимаем Install Now:
Установка Python и Pip в Ubuntu
В Ubuntu установить Python 3 можно через терминал. Запускаем его и вводим команду установки. Вторая команда выводит версию Python.
Далее устанавливаем Pip и обновляем его. После обновления необходимо перезапустить текущую сессию (или перезагрузить компьютер), иначе возникнет ошибка во время вызова Pip.
Основные команды Pip
Рассмотрим основные команды при работе с Pip в командой строке Windows и в терминале Ubuntu.
Установка VirtualEnv и VirtualEnvWrapper
VirtualEnv используется для создания виртуальных окружений для Python программ. Это необходимо для избежания конфликтов, позволяя установить одну версию библиотеки для одной программы, и другу для второй. Всё удобство использования VirtualEnv постигается на практике.
Установка VirtualEnv и VirtualEnvWrapper в Windows
В командной строке выполняем команды:
Установка VirtualEnv и VirtualEnvWrapper в Ubuntu
Для Ubuntu команда установки будет следующей:
После которой в конец
Работа с виртуальным окружением VirtualEnv
Рассмотрим основные команды при работе с VirtualEnv в командой строке Windows и в терминале Ubuntu.
| Команда | Описание |
|---|---|
| mkvirtualenv env-name | Создаем новое окружение |
| workon | Смотрим список окружений |
| workon env-name | Меняем окружение |
| deactivate | Выходим из окружения |
| rmvirtualenv env-name | Удаляем окружение |
Установка PyCharm
PyCharm — интегрированная среда разработки для языка программирования Python. Обладает всеми базовыми вещами необходимых для разработки. В нашем случае огромное значение имеет хорошее взаимодействие PyCharm с VirtualEnv и Pip, чем мы и будем пользоваться.
Установка PyCharm в Windows
Скачиваем установщик PyCharm Community для Windows с официального сайта JetBrains. Если умеете проверять контрольные суммы у скаченных файлов, то не забываем это сделать.
В самой установке ничего особенного нету. По сути только нажимаем на кнопки next, и в завершение на кнопку Install. Единственно, можно убрать версию из имени папки установки, т.к. PyCharm постоянно обновляется и указанная версия в будущем станет не правильной.
Установка PyCharm в Ubuntu
Скачиваем установщик PyCharm Community для Linux с официального сайта JetBrains. Очень хорошей практикой является проверка контрольных сумм, так что если умеете, не ленитесь с проверкой.
Теперь в директории
Далее выполняем команды в терминале:
Производим установку. И очень важно в конце не забыть создать desktop файл для запуска PyCharm. Для этого в Окне приветствия в нижнем правом углу нажимаем на Configure → Create Desktop Entry.
Установка PyCharm в Ubuntu из snap-пакета
PyCharm теперь можно устанавливать из snap-пакета. Если вы используете Ubuntu 16.04 или более позднюю версию, можете установить PyCharm из командной строки.
Использование VirtualEnv и Pip в PyCharm
Поддержка Pip и Virtualenv в PyCharm появилась уже довольно давно. Иногда конечно возникают проблемы, но взаимодействие работает в основном стабильно.
Рассмотрим два варианта работы с виртуальными окружениями:
Первый пример: использование собственного виртуального окружения для проекта
Создадим программу, генерирующую изображение с тремя графиками нормального распределения Гаусса Для этого будут использоваться библиотеки matplotlib и numpy, которые будут установлены в специальное созданное виртуальное окружение для программы.
Запускаем PyCharm и окне приветствия выбираем Create New Project.
В мастере создания проекта, указываем в поле Location путь расположения создаваемого проекта. Имя конечной директории также является именем проекта. В примере директория называется ‘first_program’.
Теперь установим библиотеки, которые будем использовать в программе. С помощью главного меню переходим в настройки File → Settings. Где переходим в Project: project_name → Project Interpreter.
Здесь мы видим таблицу со списком установленных пакетов. В начале установлено только два пакета: pip и setuptools.
Справа от таблицы имеется панель управления с четырьмя кнопками:
Для добавления (установки) библиотеки в окружение нажимаем на плюс. В поле поиска вводим название библиотеки. В данном примере будем устанавливать matplotlib. Дополнительно, через Specify version можно указать версию устанавливаемого пакета и через Options указать параметры. Сейчас для matplotlib нет необходимости в дополнительных параметрах. Для установки нажимаем Install Package.
После установки закрываем окно добавления пакетов в проект и видим, что в окружение проекта добавился пакет matplotlib с его зависимостями. В том, числе был установлен пакет с библиотекой numpy. Выходим из настроек.
Теперь мы можем создать файл с кодом в проекте, например, first.py. Код программы имеет следующий вид:
Далее указываем в поле Name имя конфигурации и в поле Script path расположение Python файла с кодом программы. Остальные параметры не трогаем. В завершение нажимаем на Apply, затем на OK.
Теперь можно выполнить программу и в директории с программой появится файл gauss.png :
Второй пример: использование предварительно созданного виртуального окружения
Данный пример можно использовать во время изучения работы с библиотекой. Например, изучаем PySide2 и нам придется создать множество проектов. Создание для каждого проекта отдельного окружения довольно накладно. Это нужно каждый раз скачивать пакеты, также свободное место на локальных дисках ограничено.
Более практично заранее подготовить окружение с установленными нужными библиотеками. И во время создания проектов использовать это окружение.
В этом примере мы создадим виртуальное окружения PySide2, куда установим данную библиотеку. Затем создадим программу, использующую библиотеку PySide2 из предварительно созданного виртуального окружения. Программа будет показывать метку, отображающую версию установленной библиотеки PySide2.
Далее в созданном окружении устанавливаем пакет с библиотекой PySide2, также как мы устанавливали matplotlib. И выходим из настроек.
Теперь мы можем создавать новый проект использующий библиотеку PySide2. В окне приветствия выбираем Create New Project.
Для проверки работы библиотеки создаем файл second.py со следующий кодом:
Далее создаем конфигурацию запуска программы, также как создавали для первого примера. После чего можно выполнить программу.
Заключение
У меня нет богатого опыта программирования на Python. И я не знаком с другими IDE для Python. Поэтому, возможно, данные IDE также умеют работать с Pip и Virtualenv. Использовать Pip и Virtualenv можно в командой строке или в терминале. Установка библиотеки через Pip может завершиться ошибкой. Есть способы установки библиотек без Pip. Также создавать виртуальные окружения можно не только с помощью Virtualenv.
В общем, я лишь поделился небольшой частью опыта из данной области. Но, если не вдаваться в глубокие дебри, то этого вполне достаточно знать, чтобы писать простые программы на Python с использованием сторонних библиотек.
Can’t make a virtual env in PyCharm using a WSL Python interpreter
I’m trying to use a Python interpreter in WSL to make virtual environments, buy it doesn’t show any Python file.
I used where python3 to find the interpreter. It says /usr/bin/python3 but as you can see it shows nothing in PyCharm.
I also tried uninstalling and reinstalling PyCharm and it didn’t work.
3 Answers 3
Sadly, Virtual Environments are not yet supported in Pycharm with WSL. See the docs here.
Excerpt: «Note that with WSL you cannot create virtual environments: all packages you install will be added to the corresponding system interpreter. You will be asked to enter your sudo password»
If I absolutely need to code against a library within Ubuntu (such as Apache Pulsar), I use Linux Pycharm running an XSession to XFCE, running withing WSL. It works very well and you will find lots of articles to achieve this with a Google Search.
You can set up venv inside wsl:
And add this to pycharm:
I am not familiar with using WSL through PyCharm, but I do use an interpreter on remote server thourgh SSH.
With my experience I know PyCharm doesn’t support creating a new venv environment from the IDE on the remote server.
The workaround I use is to first set up new venv manually within the server, and then when I set up the project interpreter in PyCharm I set the interpreter path to the relevant venv path in the server.
So I suggest the same thing- first create a new venv on the WSL environment and then set the path of the venv as the project interpreter (through WSL no through remote server)
How do I activate a virtualenv inside PyCharm’s terminal?
I’ve set up PyCharm, created my virtualenv (either through the virtual env command, or directly in PyCharm) and activated that environment as my Interpreter. Everything is working just fine.
However, if I open a terminal using «Tools, Open Terminal», the shell prompt supplied is not using the virtual env; I still have to use source
/envs/someenv/bin/activate within that Terminal to activate it.
Another method is to activate the environment in a shell, and run PyCharm from that environment. This is «workable» but pretty ugly, and means I have major problems if I switch environments or projects from PyCharm: I’m now using the totally-wrong environment.
Is there some other, much-easier way to have «Tools, Open Terminal» automatically activate the virtual environment?
27 Answers 27
According to https://www.jetbrains.com/pycharm/whatsnew/#v2016-3-venv-in-terminal, PyCharm 2016.3 (released Nov 2016) has virutalenv support for terminals out of the box
Auto virtualenv is supported for bash, zsh, fish, and Windows cmd. You can customize your shell preference in Settings (Preferences) | Tools | Terminal | check Activate virtaulenv
you also need to make sure to have the path of virtual environment path included in the content root folder of your project structure. You can go to settings (preference) | project | Project Structure | if your environment is not included in the project directory.
Use your virtualenv path as the last parameter.
Then set the shell Preferences->Project Settings->Shell path to
/pycharmenv/bin/terminalactivate sounds like a good option.
Update:
The preferences in Settings (Preferences) | Tools | Terminal are global.
If you use a venv for each project, remember to use current path variable and a default venv name:
For Windows users: when using PyCharm with a virtual environment, you can use the /K parameter to cmd.exe to set the virtual environment automatically.
«» to Shell path and add (mind the quotes). Also add quotes around cmd.exe, resulting in:
«cmd.exe» /k «»C:\mypath\my-venv\Scripts\activate.bat»»
For Windows users when using PyCharm and a virtual environment under Windows, you can use the /k parameter to cmd.exe to set the virtual environment automatically.
Go to Settings, Terminal, Default shell and add /K
I don’t have the reputation to comment on the earlier response so posting this corrected version. This really saves a LOT of time.
Update:
PyCharm 4 now has virtualenvs integrated in the IDE. When selecting your project interpreter, you can create, add, or select a virtualenv. They’ve added a «Python Console» that runs in the configured project interpreter.
If You are using windows version it is quite easy. If you already have the virtual environment just navigate to its folder, find activate.bat inside Scripts folder. copy it’s full path and paste it in pycharm’s terminal then press Enter and you’re done!
If you need to create new virtual environment :
Based on answers from Peter and experimentation, I’ve come up with a good «general solution», which solves the following:
Drop this script into a bin directory somewhere. E.g.
Then set PyCharm’s Shell path to:
I have viewed all of the answers above but none of them is elegant enough for me. In PyCharm 2017.1.3 (in my computer), the easiest way is to open Settings->Tools->Terminal and check Shell integration and Activate virtualenv options.
Thanks Chris, your script worked for some projects but not all on my machine. Here is a script that I wrote and I hope anyone finds it useful.
/.bashrc» before this script.
If you have moved your project to another directory, you can set the new path via Settings dialog. And then you need to set this Project Interpreter in the Edit Configuration dialog.
On Mac it’s PyCharm => Preferences. => Tools => Terminal => Activate virtualenv, which should be enabled by default.
/pycharmactivate. Maybe not the best solution incase you have different project and virtualenv directories/names but it works for me. This script contains the following 3 lines and assumes your virtualenv has the same name as your project dir.
and another file deactivate_env.bat:
everytime open the terminal window, just execute the bat file to activate/deactivate the virtualenv, you will stay in source code path, no need to change path to and back.
Solution for WSL (Ubuntu on Windows)
If you’re using WSL (Ubuntu on Windows), you can also open bash as terminal in pycharm and activate a linux virtualenv.
In Pycharm File > Settings > Tools > Terminal add the following ‘Shell path’:
Project specific virtualenv
BONUS: automatically open ssh tunnel to connect virtualenv as project interpreter
Now when you open your project, your bash automatically starts in your virtualenv, opens a ssh tunnel, and pycharm connects the virtualenv as remote interpreter.
Configure a Pipenv environment
Pipenv is a tool that provides all necessary means to create a virtual environment for your Python project. It automatically manages project packages through the Pipfile file as you install or uninstall packages.
Pipenv also generates the Pipfile.lock file, which is used to produce deterministic builds and create a snapshot of your working environment. This might be particularly helpful for security sensitive deployment, when project requirements and packages versions are critical. For more details about pipenv, see project documentation at pipenv.kennethreitz.org/.
To use Pipenv with PyCharm, you need to implement several preparation steps.
Install Pipenv
Run the following command to ensure you have pip installed in your system:
You should expect to receive a system response indicating the pip version. If no pip is discovered, install it as described in the Installation Instructions. Alternatively, you can download and install Python from http://python.org.
Install pipenv by running the following command:
When installation completes, you will see the following message:
For your convenience, you might add the user base’s binary directory to your PATH environmental variable. If you skip this procedure, PyCharm will prompt you to specify the path to the pipenv executable when adding a pipenv environment.
Run the following command:
A sample output can be:
Replace site-packages with Scripts in this path to receive a string for adding to the PATH variable, for example:
$ setx PATH «%PATH%;C:\Users\jetbrains\AppData\Roaming\Python\Python37\Scripts»
Run the following command to find the user base’s binary directory:
An example of output can be
/Users/jetbrains/.local (masOS) or /home/jetbrains/.local (Linux)
Add bin to this path to receive a string for adding to the
/.bashrc file, for example:
Run the following command to make the changes effective:
After the preparation steps are done, you can use pipenv to create a virtual environment for new or existing projects.
Set pipenv for a new Python project
Initiate creating a new Python project as described in Creating a pure Python project.
If you have added the user base’s binary directory to your PATH environmental variable, you don’t need to set any additional options: the path to the pipenv executable will be autodetected.
Click OK to complete the task.
Click OK to save the changes and complete the task.
You can also set up pipenv for any of your earlier created projects.
Configure pipenv for an existing Python project
Do one of the following:
Press Ctrl+Alt+S to open the project Settings/Preferences and go to Project
If you have added the user base’s binary directory to your PATH environmental variable, you don’t need to set any additional options: the path to the pipenv executable will be autodetected.
If you see the Pipenv executable is not found error message, follow the pipenv installation procedure to discover the executable path and add it to the Pipenv executable field.
Click OK to complete the task.
Once all the steps are done, the new pipenv environment is set for your project and the packages listed in the Pipfile are installed.
If you open a project with a Pipfile file added but no any interpreter configured, PyCharm offers you to use Pipenv environment.
If you select this option, PyCharm sets pipenv for you automatically. Alternatively, you can click Configure Python interpreter to follow the standard workflow.
Similarly, when you open a project with a Pipfile file in PyCharm for the very first time, for example, by checking it out from the Version Control, the Pipenv virtual environment will be configured automatically.
PyCharm can create a Pipenv environment for your project based on the project requirements recorded in the Pipfile.
Create an environment using the Pipfile
Open any directory with your source files that contains the Pipenv file: select File | Open from the main menu and choose the directory.
If no any environment has been created for this project, PyCharm suggests creating it:
If PyCharm cannot autodetect the pipenv executable, specify a path to it. Click OK to complete the task.
/.bashrc and re-login to your OS in order for all the GUI processes to inherit new environment variables from your shell config.
For any of the configured Python interpreters (but Docker-based), you can:
How to set up and use a virtual python environment in Ubuntu?
Python virtual environments are used to create isolated python environments to avoid dependency and version conflicts, and also indirectly take care of permission issues. But what is the easiest way to set it up, and use it, in Ubuntu?
4 Answers 4
With virtualenvwrapper (user friendly wrappers for the functionality of virtualenv )
Install virtualenv
Install virtualenv with
Install virtualenvwrapper
The reason we are also installing virtualenvwrapper is because it offers nice and simple commands to manage your virtual environments. There are two ways to install virtualenvwrapper :
As Ubuntu package (from Ubuntu 16.04)
Using pip
Install and/or update pip
Install pip for Python 2 with
(if you use Python 3, you may need to use pip3 instead of pip in the rest of this guide).
Optional (but recommended): Turn on bash autocomplete for pip
Because we want to avoid sudo pip we install virtualenvwrapper locally (by default under
Setup virtualenv and virtualenvwrapper:
First we export the WORKON_HOME variable which contains the directory in which our virtual environments are to be stored. Let’s make this
now also create this directory
and put this export in our
/.bashrc file so this variable gets automatically defined
We can also add some extra tricks like the following, which makes sure that if pip creates an extra virtual environment, it is also placed in our WORKON_HOME directory:
/.bashrc to load the changes
Test if it works
You will see that the environment will be set up, and your prompt now includes the name of your active environment in parentheses. Also if you now run
you should see a lot of /home/user/.virtualenv/. because it now doesn’t use your system site-packages.
You can deactivate your environment by running
and if you want to work on it again, simply type
Finally, if you want to delete your environment, type
Enjoy!
Thanks to the author of this blogpost.
Virtual environments offer a way for managing and isolating dependencies on a per-project basis. Moreover, they also avoid the whole sudo pip install situation, which is a security risk as I have explained in https://askubuntu.com/a/802594/15003. The official Python documentation also encourages the use of virtual environments.
If you would like to create a virtualenv for Python 3, replace virtualenv venv with:


















