make available to all projects pycharm что это

Создание виртуальных окружений и установка библиотек для 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. Для этого в Окне приветствия в нижнем правом углу нажимаем на ConfigureCreate 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’.

Теперь установим библиотеки, которые будем использовать в программе. С помощью главного меню переходим в настройки FileSettings. Где переходим в Project: project_nameProject 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 с использованием сторонних библиотек.

Источник

Configure a virtual environment

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

Create a virtual environment

Ensure that you have downloaded and installed Python on your computer.

Do one of the following:

Press Ctrl+Alt+S to open the project Settings/Preferences and go to Project

If New environment is selected:

If PyCharm detects no Python on your machine, it provides two options: to download the latest Python versions from python.org or to specify a path to the Python executable (in case of non-standard installation).

Select the Make available to all projects checkbox if you want to reuse this environment when creating Python interpreters in PyCharm.

If Existing environment is selected:

Select the Make available to all projects checkbox if you want to reuse this environment when creating Python interpreters in PyCharm.

Click OK to complete the task.

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

Set an existing virtual environment

Press Ctrl+Alt+S to open the IDE settings and select Project

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.

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.

Источник

Install, uninstall, and upgrade packages

PyCharm provides methods for installing, uninstalling, and upgrading Python packages for a particular Python interpreter. By default, PyCharm uses pip to manage project packages. For Conda environments you can use the conda package manager.

Manage packages in the Python Packages tool window

This tool window is available in PyCharm 2021.1 and later

The Python Packages tool window shows installed packages and the packages available in the PyPI repository. Use the Search field to filter out the list of the available packages.

You can preview package documentation in the documentation area, or you can click the Documentation link and open the corresponding resource in a browser.

Install packages from repositories

Start typing the package name in the Search field of the Python Package tool window. You should be able to see the number of the matching packages.

Expand the list of the available versions in the upper-right corner of the tool window. Select the required version or keep it the latest.

Click the Install button next to the version list. Once PyCharm notifies you about successful installation, you should see the package in the list of the installed packages.

Install packages from Version Control System

Specify a path to the target git repository. Refer to pip documentation for more information about supported path formats.

Select Install as editable (-e) if you want to install a project in editable mode (for example, setuptools develop mode ).

Install packages from a local machine

Specify a path to the package directory or an archive ( zip or whl ).

Manage packages in the Python interpreter settings

If you select a Python interpreter with the configured Conda environment, the Use Conda Package Manager toggle appears in the packages area toolbar.

Use this toggle to manage packages from the Conda environment repository. This toggle is enabled by default for Conda environments.

Install a package

In the Available Packages dialog that opens, preview the list of the available packages.

Type the name of the package to install in the Search field. The list shrinks to show the matching packages only.

If required, select the following checkboxes:

Specify version : if this checkbox is selected, you can select the desired version from the list of available versions. By default, the latest version is taken.

Options : If this checkbox is selected, you can type the pip install command-line options in the text field.

Install to user’s site packages directory

: If this checkbox is left cleared (by default), then the packages will be installed into the current interpreter package directory. If the checkbox is selected, the packages will be installed into the specified directory. This option is not available for Conda environments.

If you’ve got any or error messages, consult the Troubleshooting guide for a solution.

Uninstall a package

In the list of the packages, select the packages to be removed.

Click Uninstall ( ). The selected packages are removed from disk.

Upgrade a package

In the list of the packages, select the package to be upgraded.

The selected packages are upgraded to the latest available versions.

Click OK to complete upgrading.

If you’re accustomed to installing packages from the commands line, you can proceed with your workflow using the Terminal.

Reuse installed packages

Create a new virtual environment and install packages that you want to be used in other projects. Then you can specify this virtual environment as a Python interpreter for the target project and all the needed packages will be available.

In the Terminal window execute the following command:

Источник

Configure a Python interpreter

Python interpreters in PyCharm

Python interpreters can be configured for a new project or for the current project (you can create a new interpreter or use one of the existing interpreters).

Setting an existing Python interpreter

Change the Python interpreter using the Python Interpreter selector

The Python Interpreter selector is located on the status bar. It is the most convenient and quickest way to switch the Python interpreter. Just click it and select the target interpreter:

Change the Python interpreter in the project settings

Press Ctrl+Alt+S to open the IDE settings and select Project

Select the target interpreter.

When PyCharm stops supporting any of the outdated Python versions, the corresponding Python interpreter is marked as unsupported.

When you change an SSH interpreter, you might need to synchronize local content with the target server. Mind a notification balloon in the lower-right corner. You can click one of the links to perform the following actions:

Auto-upload files to the server

Synchronize files and then enable auto-uploading

Modify a Python interpreter

Press Ctrl+Alt+S to open the IDE settings and select Project

You can specify an alternative interpreter name for the selected interpreter. The Python interpreter name specified in the Name field, becomes visible in the list of available interpreters. Click OK to apply the changes.

For remote interpreters (that are available in PyCharm Professional ) you can modify configuration parameters.

Creating a new Python interpreter

To add a new interpreter to the current project:

Do one of the following:

Press Ctrl+Alt+S to open the project Settings/Preferences and go to Project

Choose the interpreter type to add and perform the specific settings:

Note that SSH, WSL, Vagrant, Docker, and Docker Compose are available only for the commercial version of PyCharm. WSL is Windows specific.

If New environment is selected:

If PyCharm detects no Python on your machine, it provides two options: to download the latest Python versions from python.org or to specify a path to the Python executable (in case of non-standard installation).

Select the Make available to all projects checkbox if you want to reuse this environment when creating Python interpreters in PyCharm.

If Existing environment is selected:

Select the Make available to all projects checkbox if you want to reuse this environment when creating Python interpreters in PyCharm.

Click OK to complete the task.

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.

If Poetry environment is selected:

If Existing environment is selected:

Click OK to complete the task.

If New environment is selected:

Select the Python version from the list.

Select the Make available to all projects checkbox if you want to reuse this environment when creating Python interpreters in PyCharm.

If Existing environment is selected:

Select the Make available to all projects checkbox if you want to reuse this environment when creating Python interpreters in PyCharm.

Click OK to complete the task.

If PyCharm detects no Python on your machine, it provides two options: to download the latest Python versions from python.org or to specify a path to the Python executable (in case of non-standard installation).

You will need admin privileges to install, remove, and upgrade packages for the system interpreter. When attempting to install an interpreter package through an intention action, you might receive the following error message: As prompted, consider using a virtual environment for your project.

Click OK to complete the task.

In the next dialog window, provide the authentication details to connect to the target server.

Select Password or Key pair (OpenSSL or PuTTY) and enter your password or passphrase. If Key pair (OpenSSL or PuTTY) is selected, specify:

Private key file : location of the file with a private key

Passphrase : similar to a password, it serves to encrypt the private key.

The RFC 4716 format for OpenSSH keys is not supported by PyCharm. See the workaround.

Click Next to proceed with the final configuration step.

You can also select the lowest checkbox to enable automatic upload of the local changes to the remote server.

In the left-hand pane of the Add Python Interpreter dialog, click Vagrant :

This results in showing the link to Vagrant host URL.

The Python interpreter path field displays the path to the desired Python executable. You can accept default, or specify a different one.

Select the Linux distribution and specify the path to the python executable in the selected Linux distribution. Typically, you should be looking for wsl.exe but you can specify any non default WSL distro.

Python interpreter path should have the default value:

Click OK to complete the task.

In the dialog that opens, select the Docker Compose option, from the drop-down lists select the Docker server, Docker Compose service (here web ), configuration file (here docker-compose.yml ) and Python interpreter path (here python ).

Next, wait while PyCharm starts your Docker Compose configuration to scan and index:

Click OK to complete the task.

When a remote Python interpreter is added, at first the PyCharm helpers are copied to the remote host. PyCharm helpers are needed to run remotely the packaging tasks, debugger, tests and other PyCharm features. Next, the skeletons for binary libraries are generated and copied locally. Also all the Python library sources are collected from the Python paths on a remote host and copied locally along with the generated skeletons. Storing skeletons and all Python library sources locally is required for resolve and completion to work correctly. PyCharm checks remote helpers version on every remote run, so if you update your PyCharm version, the new helpers will be uploaded automatically and you don’t need to recreate remote interpreter. SFTP support is required for copying helpers to the server.

Setting the default interpreter

In PyCharm, you can specify an interpreter that will be automatically set for all newly created projects.

From the main menu, select File | New Projects Setup | Settings for New Projects (on Window and Linux) or File | New Projects Setup | Preferences for New Projects (on macOS).

The change will become effective for all newly created projects in PyCharm.

Managing interpreter packages

For each interpreter, you can install, upgrade, and delete Python packages. By default, PyCharm uses pip to manage project packages. For Conda environments you can use the Conda package manager.

Источник

Читайте также:  какой климатический пояс в краснодаре
Сказочный портал