Как добавить интерпретатор python в pycharm
Перейти к содержимому

Как добавить интерпретатор python в pycharm

  • автор:

Configure a system interpreter

To work with your Python code in PyCharm, you need to configure at least one interpreter. A system interpreter is the one that comes with your Python installation. You can use it solely for all Python scripts or take it as a base interpreter for Python virtual environments.

Configure a system interpreter

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

Installing Python on Windows from Microsoft Store

Python interpreter installed from the Windows store

If you are on Windows, you can download Python from the Microsoft Store and install it as a Python interpreter. Once the Python application is downloaded from the Microsoft Store, it becomes available in the list of the Python executables. Note that interpreters added from the Microsoft Store installations come with some limitations. Because of restrictions on Microsoft Store apps, Python scripts may not have full write access to shared locations such as TEMP and the registry.

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 System Interpreter .

In the Interpreter field, type the fully-qualified path to the required interpreter executable, or click and in the Select Python Interpreter dialog that opens, choose the desired Python executable.

Selecting the Python executable

System Interpreter warning message

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.

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

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:

Настройка интерпретатора Python

Чтобы работать с кодом Python в PyCharm, вам необходимо настроить по крайней мере один интерпретатор Python. Вы можете использовать системный интерпретатор, доступный при установке Python. Вы также можете создать виртуальную среду Virtualenv, Pipenv или Conda. Виртуальная среда состоит из базового интерпретатора и установленных пакетов.

С помощью PyCharmProfessional вы также можете настроить интерпретаторы для выполнения кода Python в удаленных средах: SSH, Vagrant, WSL (только для Windows), Docker и DockerCompose.

Интерпретаторы Python

При настройке интерпретатора Python необходимо указать путь к исполняемому файлу Python в вашей системе. Итак, перед настройкой интерпретатора Python вам необходимо убедиться, что вы загрузили Python и установили его в своей системе, и вы знаете путь к нему.

Вы можете создать несколько интерпретаторов Python на основе одного и того же исполняемого файла Python. Это полезно, когда вам нужно создать различные виртуальные среды для разработки различных типов приложений. Например, вы можете создать одну виртуальную среду на основе Python 3.6 для разработки приложений Django и другую виртуальную среду на основе того же Python 3.6 для работы с научными библиотеками.

Интерпретаторы Python могут быть настроены для нового проекта или для текущего проекта (вы можете создать новый интерпретатор или использовать один из существующих ).

Настройка существующего интерпретатора Python

В любое время вы можете переключить интерпретатор Python либо с помощью селектора интерпретаторов Python, либо в настройках/настройках проекта.

Селектор интерпретатора Python находится в строке состояния. Это самый удобный и быстрый способ переключения интерпретатора Python. Просто нажмите на него и выберите целевой интерпретатор:\

Настройка интерпретатора Python

Измените интерпретатор Python в настройках проекта

  1. Нажмите Ctrl+Alt+S, чтобы открыть настройки IDE, и выберите Проект | Интерпретатор Python.
  2. Разверните список доступных переводчиков и нажмите ссылку «Показать все». Затем, щёлкните значок Настроить интерпретатор проекта и выберите «Показать все». Настройка интерпретатора Python
  3. Выберите целевой интерпретатор. Настройка интерпретатора Python

Когда PyCharm прекращает поддерживать любую из устаревших версий Python, соответствующий интерпретатор Python помечается как неподдерживаемый.

Примечание: При изменении интерпретатора SSH PyCharm отображает параметры соответствующей конфигурации развертывания. Не рекомендуется выбирать опцию SSH, так как она не позволяет синхронизировать файлы и является частью устаревшей реализации.

Лучшие интерпретаторы Python 2021 года

Нет никаких сомнений в том, что Python является одним из самых популярных языков программирования. За последние несколько лет он быстро завоевал популярность среди мирового сообщества разработчиков. CPython является интерпретатором Python по умолчанию, тем не менее, доступны и другие варианты.

Python — это язык программирования высокого уровня, что означает, что его код написан в удобочитаемой форме. Тем не менее, компьютер не понимает язык высокого уровня, ему требуется переводчик для преобразования кода высокого уровня в машинный код, чтобы ОС могла выполнять то же самое. Вот тут-то и появляется переводчик.

Vamware

Python использует интерпретатор в качестве инструмента перевода для компьютера для перевода и выполнения кода высокого уровня. Когда мы устанавливаем Python в нашей системе, мы устанавливаем интерпретатор Python, облегчающий чтение и выполнение Python.

В этой статье мы составили шорт-лист из 5 лучших интерпретаторов Python, которые идеально подходят для использования с языком программирования высокого уровня. Но перед этим давайте поговорим о переводчике.

Что такое интерпретатор?

Интерпретатор-это компьютерная программа, которая непосредственно выполняет программный код, не меняя его на машинный язык или байт-код. В отличие от компилятора, интерпретатор не создает отдельный файл для байтового кода, вместо этого он непосредственно выполняет исходный код.

5 Лучших вариантов интерпретатора Python (Реализация Python)

Оригинальная реализация Python, которая широко используется сообществом Python и которая присутствует на официальном сайте python, реализована с использованием языка программирования C. Вот почему мы называем его CPython.

Как и CPython, существует множество других реализаций – интерпретаторов – доступных для языка программирования Python. Очевидно, что не все из них хороши в использовании. Итак, вот наш список из 5 лучших интерпретаторов Python на 2021 год, которые вы можете изучить и использовать для расширения своих знаний по python:

  • CPython
  • PyPy
  • StacklessPython
  • Jython
  • IronPython

Давайте пройдем вперед и подробно обсудим каждый из них:

CPython (интерпретатор Python по умолчанию)

Cpython
GitHub: https://github.com/python/cpython
Поддерживается версиями Python 3.x

Он поставляется в качестве интерпретатора Python по умолчанию, если вы устанавливаете Python с официального сайта. Поступая таким образом, вы в конечном итоге устанавливаете CPython в качестве интерпретатора.

CPython написан на языках программирования C и Python, вот как он получил свое название. Кроме того, если мы посмотрим на общее использование Python по всему миру, CPython является наиболее широко используемой реализацией языка программирования высокого уровня.

Разработанный основными разработчиками и сообществом Python, CPython поддерживается Фондом программного обеспечения Python. Хотя это интерпретатор, он также действует как компилятор. Это потому, что он выполняет некоторые операции компиляции, преобразует код Python в байт-код, а затем использует интерпретатор для их выполнения. Все это происходит виртуально, поэтому технически это не компилятор.

Итак, если вы пишете код Python, которым хотите поделиться с сообществом в качестве проекта с открытым исходным кодом, вы должны ориентироваться на пользователей CPython, потому что он, очевидно, имеет самый широкий охват.

PyPy

https://pypy.org/
Поддерживается версиями Python 2.x и 3.x

PyPy — это мощная, быстрая и полностью совместимая реализация языков программирования Python. Кроме того, он считается альтернативой № 1 для CPytho. По сравнению с CPython, PyPy быстрее, потому что это компилятор just-in-time (JIT). CPython, напротив, является интерпретатором. Любой код Python может работать на PyPy, за исключением того, который зависит от расширения CPython.

Хотя PyPy является интерпретатором, внутренне он использует мета-трассировку, метод, который превращает интерпретатор в компилятор точно в срок. Работать с интерпретаторами очень легко, но они обычно выполняют код медленнее, чем компиляторы. Следовательно, PyPy решает эту проблему для интерпретаторов Python, превращаясь в JIT-компилятор.

PyPy настоятельно рекомендуется для тех, кто хочет повысить производительность своей программы. Более того, если вы запустите свою программу на Python с помощью PyPy, она будет потреблять меньше памяти, чем CPython.

StacklessPython

РепоPythonGitHub без стека: https://github.com/stackless-dev/stackless
Поддерживается версиями Python 3.x

StacklessPython — это еще один мощный интерпретатор языка программирования python. Как и CPython, он также написан на C и Python. Как следует из названия, StacklessPython избегает стека вызовов C. Стек вызовов-это структура данных стека, которая содержит подпрограммы и определяет поток управления вызовами функций. Хотя StacklessPython избегает вызовов стека, он использует стек для вызовов функций.

В дополнение к другим функциям, StacklessPython также добавляет поддержку сопрограмм, каналов связи и сериализации задач. Микро-поток — самая важная особенность StacklessPython. Это позволяет избежать значительной части накладных расходов, связанных с обычными потоками операционной системы.

Вывод

Интерпретаторы Python-это различные реализации Python для облегчения разработки в соответствии с различными языками программирования. CPython — это широко используемая реализация/интерпретатор, предлагаемая официальнымPython.

Для разработчика python также очень важно знать другие реализации Python. Мы надеемся, что эта статья о лучших 5 интерпретаторах Python дала вам достаточно знаний о различных интерпретаторах python, в частности, и о работе интерпретатора python в целом.

Installing Python with PyCharm

PyCharm is our favorite IDE for developing applications with Python. With the release of PyCharm 2020.1, PyCharm can now install the Python interpreter automatically if it does not detect an existing installation. I wasn’t able to try this feature out as I already have several versions of Python installed on my primary computer. I recently picked up a Microsoft Surface Go 2 which provided the perfect opportunity to start installing Python with PyCharm.

Installing the Python Interpreter

PyCharm allows you to create a new virtual environment when you create a new Python project. If Python is not already installed, the base interpreter will give you the option to download the latest build from one of the two most recent major versions of Python.

python

After clicking the Create button, PyCharm will download and install the selected version of Python, create the virtual environment, and open up the new project.

Questions… and Answers

Normally I’d start developing the new project, but at this point I had a lot of questions. Where is Python installed? Which features were installed with it? Is the new installation in my path?

PyCharm will download the 64 bit executable installer for the version you selected. It then runs the installer with the default options selected in quiet mode. Quiet mode hides the installer’s user interface.

Python will be installed in \Users\\AppData\Local\Programs\Python\PythonXX where <username> is the username for the current user and XX is the version of Python you selected.

The installed features include IDLE, pip, and the documentation.

Installation will NOT be in your path. This means if you open the command prompt or Terminal and type Python, you will not the get Python interpreter you just installed. Instead the Windows Store will open and prompt you to install Python 3. More on this later.

Uninstalling Python

The Python interpreter installed by PyCharm will appear in the list of apps and features and can be uninstalled like any other program.

uninstalling python

Installing Python from the Windows Store

Starting with the May 2019 update to Windows 10, you will be prompted to install Python 3 from the Windows Store if a Python interpreter is not already in your path. You can read more about this here.

python windows store

You can disable this feature with the following steps:

  1. Open Settings and choose Apps
  2. Click App execution aliases
  3. Turn off all of the entries for Python (there may be more than one)

Installing Additional Python Versions

Once you have a system-wide Python interpreter installed, you will not be able to install another version from within PyCharm. Although there has been some discussion regarding this in the issue tracker, the PyCharm team doesn’t seem keen on adding this feature.

Your best bet is to head over to python.org and download the installer for additional versions.

If you need help creating or implementing custom software, give us a call – 586.263.1775.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *