inherit global site packages pycharm что это

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.

Источник

How to create a Virtual environment in PyCharm?

If you are a newbie to python, you probably need to learn how to create a virtual environment for your python project. So, this article is for you 💙

What is a virtual environment?

In Python, a virtual environment creates an isolated environment for each project. By doing this, every project can have its own dependencies regardless of what dependencies the other project are employing.

Why do developers need virtual environments?

Let’s understand the question of “why?” with a simple example:

Imagine that you are working with 2 projects, project A and project B. Project A works with TensorFlow 1.10.0 while project B works with TensorFlow 2.3.0. In such situations, installing the versions globally may create conflicts. Therefore in such situations, maintaining dependencies of each project in isolation is very useful.

As you now know why virtual environments are required, let’s get started with creating one!

Step 1: Create a new project

Create a new project and give it a name

Then, select the radio button with the label “New environment using” and select Virtualenv from the dropdown.

Step 2: Create a virtual environment

Next, give a location to the virtual environment and select the base interpreter.

Here, if you check the checkbox labelled “Inherit global site-packages”, all the globally installed libraries and packages will be inherited by this project’s virtual environment.

When you click on the “Create” button, the virtual environment will be created.

Once the virtual environment is created, you can see the venv directory under your project folder (see the image below).

Bravo! you have now created the virtual environment for your project.

Any edits, deletes or installations of new packages to this virtual environment will only be available for the particular project. It will not interfere with the other projects that you work on.

Step 03: Installing a package to the virtual environment

As the virtual environment is now set up, you can install any library into it by using the command

Example: I am installing NumPy to my virtual environment

Now, if you go to File → Settings →Project →Project Interpreter, you can see NumPy installed in my virtual environment

Now you can continue with your project and install dependencies without interfering other projects.

Hope you learnt something useful 😊

Источник

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

Источник

Make a PyCharm project inheriting global site-packages, after creating the project?

I’m a newbie with PyCharm and Mac OS. I created a python project in PyCharm with VirtualEnv, and I didn’t select the option of ‘Inherit global site packages’. After working on this project for a while, I realized I need to inherit some packages that are installed globally.

There is a workaround here, which creates a shared Virtual Environment and uses it: Create shared virtual env. However, I wonder whether there is any way to make changes to current project, rather than creating a new project or creating a shared virtual environment?

A separate question: assuming that I have a project that inherits global packages. If after the project’s creation, I installed other packages globally, will those packages available in this project?

1 Answer 1

I figured this out when clicking around.

Then choose «Show all. «, and select the virtual environment you want to change, click this icon to add global packages’ path into this venv’s path

then click ok or apply to make it work. Usually, your global packages’ path is «/path-to-python/Lib/site-packages», for my desktop is:

Now you can use all your global packages within the venv. For any system other than Windows, this should work fine as well.

But you won’t see any global packages in pycharm’s package viewer for this venv, which totally makes sense, because pycharm can only manager the venv for you, not the global one.

For your separate question: Yes. Because you only add global path into your venv, not like copying all package files into it. After adding the global path, all global packages should work inside your venv at any time.

Источник

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.

Источник

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