Как найти интерпретатор python в pycharm

Python interpreters in PyCharm

To work with your Python code in PyCharm, you need to configure at least one Python interpreter. You can use a system interpreter that is available with your Python installation. You can also create a Virtualenv, Pipenv, Poetry, or Conda virtual environment. A virtual environment consists of a base interpreter and the installed packages.

With PyCharm Professional, you can also configure interpreters to execute your Python code on remote environments by using SSH, Vagrant, Docker, Docker Compose, or WSL (only for Windows).

Python interpreters

When you configure a Python interpreter, you need to specify the path to the Python executable in your system. So, before configuring a Python interpreter, you need to ensure that you’ve downloaded Python and installed it in your system and you’re aware of a path to it. You can create several Python interpreters based on the same Python executable. This is helpful when you need to create different virtual environments for developing different types of applications. For example, you can create one virtual environment based on Python 3.6 to develop Django applications and another virtual environment based on the same Python 3.6 to work with scientific libraries.

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).

Configuring an existing Python interpreter

At any time, you can switch the Python interpreter either by using the Python Interpreter selector or in Settings.

Switch 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:

    Project interpreter selector

Switch the Python interpreter in the IDE settings

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

  2. Expand the list of the available interpreters and click Show All.

    Show all available interpreters

  3. Select the target interpreter.

    View interpreters

    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 the local content with the target server. Mind a notification balloon in the lower-right corner:

Sync local files with the deployment server

You can choose to perform one of the following actions:

  • Auto-upload files to the server

  • Synchronize files and then enable auto-uploading

Modify a Python interpreter

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

  2. Expand the list of the available interpreters and click Show All.

    Show all available interpreters

  3. You can modify the path to the Python executable in the Interpreter path field.

    To change the interpreter name, select the target interpreter and click App actions edit.

    Edit icon

    The Python interpreter name specified in the Name field, becomes visible in the list of available interpreters. Click OK to apply the changes.

    Edit interpreter settings

Remove a Python interpreter

If you no longer need a Python interpreter for a project, you can remove it from the project settings.

  1. Do one of the following:

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

    • Click the Python Interpreter selector and choose Interpreter Settings.

  2. Expand the list of the available interpreters and click Show All.

    Show all available interpreters

  3. Choose the interpreter that you want to remove and click Remove Interpreter.

    Remove a Python interpreter

Creating a new Python interpreter

Configuring local Python interpreters

To configure a local Python interpreter for the current project, follow one of the procedures below:

Configure a system interpreter

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

    Installing Python on Windows from Microsoft 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.

    Python interpreter installed from the Windows store 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.

  2. 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 . 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.

  3. Select Add Local Interpreter.

  4. In the left-hand pane of the Add Python Interpreter dialog, select System Interpreter.

    Adding a system interpreter

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

    Selecting the Python executable

    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:

    System Interpreter warning message As prompted, consider using a virtual environment for your project.

  6. Click OK to complete the task.

For more information, see Configure a system interpreter.

Create a virtualenv environment

  1. 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 . 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.

  2. Select Add Local Interpreter.

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

    Creating a virtual environment

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

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

    • Choose the base interpreter from the list, or click Choose the base interpreter 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.

    Existing virtual environment
    • Choose the desired interpreter from the list.

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

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

  5. Click OK to complete the task.

For more information, see Configure a virtual environment.

Create a conda environment

  1. Ensure that Anaconda or Miniconda is downloaded and installed on your computer, and you’re aware of a path to its executable file.

    Refer to the installation instructions for more details.

  2. 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 . 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.

  3. Select Add Local Interpreter.

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

    New Conda environment

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

    New conda environment
    • Select the Python version from the list.

    • Normally, PyCharm will detect conda installation.

      Otherwise, specify the location of the conda executable, or click Conda executable location to browse for it.

    • Specify the environment name.

    Existing conda environment
    • Choose the desired environment from the list.

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

  6. Click OK to complete the task.

For more information, see Configure a conda virtual environment.

Create a pipenv environment

  1. 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 . 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.

  2. Select Add Local Interpreter.

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

    Adding a Pipenv environment

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

  5. If you have added the base 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 the pipenv executable is not found, follow the pipenv installation procedure to discover the executable path, and then paste it in the Pipenv executable field.

  6. 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.

Pipenv inspection

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.

When you have set the Pipenv virtual environment as a Python interpreter, all available packages are added from the source defined in Pipfile . The packages are installed, removed, and updated in the list of the packages through pipenv rather than through pip.

For more information, see Configure a Pipenv environment.

Create a Poetry environment

  1. 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 . 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.

  2. Select Add Local Interpreter.

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

    creating a poetry environment

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

    New Poetry environment
    • Select Poetry Environment.

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

    • If PyCharm doesn’t detect the poetry executable, specify the following path in the Poetry executable field, replacing jetbrains with your username:

      /Users/jetbrains/Library/Application Support/pypoetry/venv/bin/poetry

      C:UsersjetbrainsAppDataRoamingpypoetryvenvScriptspoetry.exe

      /home/jetbrains/.local/bin/poetry

    Existing Poetry environment
    • Make sure that the project directory contains a pyproject.toml file.

    • Select Existing environment. Then expand the Interpreter list and choose the desired interpreter.

    • If the desired interpreter is not on the list, clickApp general ellipsis, and then browse for the Python executable within the previously configured Poetry environment.

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

  5. Click OK to complete the task.

For more information, see Configure a Poetry environment.

Configuring remote Python interpreters

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.

Configure a WSL interpreter

  1. 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 . 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.

  2. Select On WSL.

  3. Wait until PyCharm detects Linux on your machine and completes introspection. Press Next to proceed:

    Detecting Linux

  4. In the left-hand pane of the dialog, select the type of the WSL interpreter you want to create: Virtual Environment, Conda Environment, or System Interpreter.

    New WSL interpreter

    For a system interpreter, just provide the path to the Python executable in the selected Linux distribution.

    For virtual and conda environments, you can provide a path to a Python executable of an existing environment in the selected Linux distribution or create a new environment based on the specified Python.

Once done, the new interpreter will be added to your project, and the default mnt mappings will be set.

For more information, see Configure an interpreter using WSL.

Configure an interpreter using Vagrant

  1. Ensure that the following prerequisites are met (outside of PyCharm):

    • One of supported Vagrant providers is installed on your computer.

    • Vagrant is installed on your computer, and all the necessary infrastructure is created.

    • The parent folders of the following executable files have been added to the system PATH variable:

      • vagrant.bat or vagrant from your Vagrant installation. This should be done automatically by the installer.

      • VBoxManage.exe or VBoxManage from your Oracle’s VirtualBox installation.

    • The required virtual boxes are created.

  2. Make sure that the Vagrant plugin is enabled.

  3. Ensure that you have properly initiated and started Vagrant. Basically, you need to open the Terminal window and execute the following commands:

    $ vagrant init ubuntu/trusty64

    and

    $ vagrant up

    See Vagrant documentation for more information.

  4. 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 . 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.

  5. Select On Vagrant.

  6. Specify the path to the Vagrant instance folder in Vagrant Instance Folder.

    Wait until you see a link in Vagrant Host URL.

  7. In the New Target: Vagrant dialog, click the browse icon the Browse button next to the Vagrant Instance Folder field, and specify the desired Vagrant instance folder.

    This results in showing the link to Vagrant Host URL.

    Specifying the Vagrant instance folder

  8. In the next field, PyCharm will display the path to the Python executable. Press «Next» to proceed.

    Python executable is discovered

  9. You can create a virtual environment (venv or conda) or use a system Python interpreter for the target Vagrant instance. Note that virtual environment must be configured and available in the specified Vagrant instance folder. Otherwise, the corresponding lists will be empty.

    Virtual environment on a target Vagrant instance

    Clik Create to complete the task.

For more information, see Configure an interpreter using Vagrant.

Configure an interpreter using SSH

  1. Ensure that there is an SSH server running on a remote host, since PyCharm runs remote interpreters via ssh-sessions.

  2. 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 . 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.

  3. Select On SSH.

  4. Select an option to create a new SSH connection, then specify server information (host, port, and username).

    adding an interpreter via SSH

    Alternatively, you can select Existing and choose any available SSH configuration from the list. To create a new SSH configuration, follow the steps below:

    Creating an SSH configuration
    • Click Browse button next to the list of configurations:

      Add new SSH configuration

    • Clicknew configuration, disable the Visible only for this project checkbox, and fill in the required fields:

      Adding new SSH configuration

    • Once done, the newly created SSH configuration will appear in the list of available configurations. It will also become available in the SSH Deployment Configurations settings. Click Next to proceed:

      Connecting to SSH server

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

    specifying authentication details

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

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

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

    Click Next to proceed.

  6. Wait until PyCharm completes the introspection of the SSH server.

    SSH server introspection

  7. In the next dialog, select a type of Python environment to configure on the SSH server.

    Selecting a Python environment

    You can create a new virtual environment, select an existing one, or use a system interpreter.

    • 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.

    • You can configure the path mappings between your local project and the server. To do that, click the Browse icon in the Sync folders field and enter the path to the local project folder and the path to the folder on the remote server.

    Click Create to complete adding the interpreter.

For more information, see Configure an interpreter using SSH.

Configure an interpreter using Docker

  1. 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 . 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.

  2. Select On Docker.

  3. Select an existing Docker configuration in the Server dropdown.

    Alternatively, select Create new and perform the following steps to create a new Docker configuration:

    Create a Docker configuration

    Click New to add a Docker configuration and specify how to connect to the Docker daemon.

    The connection settings depend on your Docker version and operating system. For more information, see Docker connection settings.

    The Connection successful message should appear at the bottom of the dialog.

    Docker connection settings

    For more information about mapping local paths to the virtual machine running the Docker daemon when using Docker on Windows or macOS, see Virtual machine path mappings for Windows and macOS hosts. You will not be able to use volumes and bind mounts for directories outside of the mapped local path.

    This table is not available on a Linux host, where Docker runs natively and you can mount any directory to the container.

  4. The following actions depend on whether you want to pull a pre-built image from a Docker registry or to build an image locally from a Dockerfile.

    Pull a Docker image

    Select Pull and specify the tag of the desired image in the Image tag field.

    Creating a Docker interpreter by pulling an image

    Build a Docker image

    Select Build and change the default values in the Dockerfile and Context folder fields if necessary.

    Creating a Docker interpreter by building an image

    If required, expand the Optional section and specify the following:

  5. Wait for PyCharm to connect to the Docker daemon and complete the container introspection.

    Docker container introspection is completed

  6. Next, select an interpreter to use in the Docker container. You can choose any virtualenv or conda environment that is already configured in the container or select a system interpreter.

    Selecting a system interpreter for a Docker target

  7. Click OK.

    The configured remote interpreter is added to the list.

For more information, see Configure an interpreter using Docker.

Configure an interpreter using Docker Compose

  1. 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 . 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.

  2. Select On Docker Compose.

  3. Select an existing Docker configuration in the Server dropdown.

    Alternatively, select Create new and perform the following steps to create a new Docker configuration:

    Create a Docker configuration

    Click New to add a Docker configuration and specify how to connect to the Docker daemon.

    The connection settings depend on your Docker version and operating system. For more information, see Docker connection settings.

    The Connection successful message should appear at the bottom of the dialog.

    Docker connection settings

    For more information about mapping local paths to the virtual machine running the Docker daemon when using Docker on Windows or macOS, see Virtual machine path mappings for Windows and macOS hosts. You will not be able to use volumes and bind mounts for directories outside of the mapped local path.

    This table is not available on a Linux host, where Docker runs natively and you can mount any directory to the container.

  4. In Configuration files, specify the docker-compose.yml file. Also select the service.

    Creating a new Docker Compose target

    Optionally, specify environment variables.

  5. Wait until PyCharm creates and configures a new target:

    Configuring
                                    a Docker Compose target

  6. Next, select an interpreter to use in the container. You can choose any virtualenv or conda environment that is already configured in the container, or select a system interpreter.

    Selecting a system interpreter for a Docker target

  7. Click OK.

    The configured remote interpreter is added to the list.

For more information, see Configure an interpreter using Docker Compose.

Setting the default interpreter

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

  1. From the main menu, select (on Window and Linux) or (on macOS).

  2. Select Python Interpreter settings. Then either choose an existing interpreter from the Python interpreter list of click New interpreter to add a new interpreter. Click OK to save the changes.

    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.

Managing packages

PyCharm smartly tracks the status of packages and recognizes outdated versions by showing the number of the currently installed package version (column Version), and the latest available version (column Latest version). When a newer version of a package is detected, PyCharm marks it with the arrow sign New version is available and suggests to upgrade it.

By default, the Latest version column shows only stable versions of the packages. If you want to extend the scope of the latest available versions to any pre-release versions (such as beta or release candidate), click Show early releases.

You can upgrade several packages at once. Hold Cmd (macOS) or Ctrl on (Unix or Windows), left-click to select several items in the list of packages, and then click Upgrade.

See the detailed instructions:

  • How to install a package

  • How to upgrade the package

  • How to uninstall the package

Last modified: 03 March 2023

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

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

    Installing Python on Windows from Microsoft 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.

    Python interpreter installed from the Windows store 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.

  2. 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 . 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.

  3. Select Add Local Interpreter.

  4. In the left-hand pane of the Add Python Interpreter dialog, select System Interpreter.

    Adding a system interpreter

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

    Selecting the Python executable

    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:

    System Interpreter warning message As prompted, consider using a virtual environment for your project.

  6. Click OK to complete the task.

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

  • Manage interpreter paths
  • Install, uninstall, and upgrade packages

Last modified: 02 December 2022

I’m new to programming and just started a course on Python. I want to use PyCharm, so I downloaded and intalled it (v. 4.5, community edition). I had previously installed Python 3.5 64-bit from python.org (I’m using Windows 10).

To start using PyCharm, I need a project interpreter, which I can select in the settings. As far as I’m concerned, the interpreter is «py.exe», but when I select it, I get this error message: «The selected file is not a valid home for Python SDK». I also tried to use every file whose name contained «python» or «py», and failed.

On every website and video I see, they select a file called «python.exe», but they’re using Python 3.4 or a previous version. I checked that PyCharm supports 3.5 («Initial support for Python 3.5»).

Is there anything I’m doing wrong? What should I do to be able to use PyCharm?

All replies are appreciated. Thanks in advance.

asked Sep 28, 2015 at 21:23

Asier R.'s user avatar

file > new project settings > project Interpreter > click in the drop down and select ‘show all’ > click the ‘+’ button >

Now, in the Virtualenv Environment tab under the New environment radio button, check the path in the ‘Base interpreter:’ field. For me, mine was set to an invalid path. Once I had corrected the path to point to python.exe I recreated my new project and PyCharm built the virtualenv.

For me there was a bit more too…. When creating the new project I expanded the drop down and had to verify the directory where the venv directory was being created. Once I had corrected the path here I had to click around a bit to get it to let me create the project.

I’m going to chaulk this up to a bug. I’m using Community edition.

answered Apr 22, 2019 at 15:37

DonkeyKong's user avatar

DonkeyKongDonkeyKong

98513 silver badges18 bronze badges

When creating a project in PyCharm, if the interpret is not already selected, in the drop down menu under the projects «Location:», you can click the gear-looking icon to the right of the interpreter option, and click «Add Local»; then select the file location of the python.exe file that you have installed. It will probably be C:Python35Python.exe

answered Sep 28, 2015 at 21:38

xponent's user avatar

xponentxponent

1512 gold badges2 silver badges10 bronze badges

2

I faced a Similar issue and was not able to find Python interpreter anywhere on the system.

The problem with it was that python was installed directly with default settings and there was no exe found in

C:Python35 

and to solve this i tried uninstalling and reinstalling with custom settings and selecting allow for all users as well which did the trick and path was set correctly to

C:Python35python.exe.

After whichPycharm was able to detect the interpreter on this path.

Sanoop Surendran's user avatar

answered Sep 5, 2016 at 6:05

Anmol G's user avatar

PyCharm project interpreter problem Resolved
I installed anaconda python distribution (Anaconda3-5.0.1-Windows-x86_64.exe) from the anaconda website. https://anaconda.org/anaconda/python
What it actually did was it re-installed my Python3.6.3 (pertinent to mention I have windows10, with pyCharm community & python 3.5 already but with the interpreter problem and while installing anaconda I chose the following settings and disabled my antivirus before my anaconda installation):

  1. selecting allow for all users
  2. installation path was set correctly and (stored safely for future)
  3. restart my Computer after installation.(not essential-but I did)
  4. opened Anaconda & Jet brian pycharm
  5. selected new project in PyCharm screen shot of my New project default Python interpreter location = C:UsersSkboyPycharmProjectsdani Interpreter = C:UsersSkboyAppDataLocalProgramsPythonPython36-32python.exe

Wow! my pyCharm started working for me,

Resolution : Python6.3 re-installation with proper custom setting

make a python test test1.py program file to print «hello python test world»

Run

now my Python Interpreter(automatically -by default select) Python 3.6.3
edit configuration & check for interpreter

(C:Usersuser1AppDataLocalProgramsPythonPython36-32python.exe)

Run
success test Run
worth to mention Anaconda Jupyter is a web based can also be used in case novice user are still having problems

JohnS's user avatar

JohnS

1,1721 gold badge11 silver badges22 bronze badges

answered Dec 6, 2017 at 17:54

Waseem A's user avatar

I have had the exact same problem and was unable to find the solution until just now. Hopefully this works for anyone that was struggling with it.

I went to the location of the Python 3.5 (32-Bit) in my C: Drive which it turns out is just a shortcut to the actual Python application, right click on it and select Open file location which should direct you to the application version of python — simply called ‘python’. This is the .exe file that PyCharm was looking for to use as the interpreter.

Now go to the configure interpreter menu in Pycharm and type in the file location of the actual python application. To get to mine I had to go to AppData/Local/Programs/Python/Python35-32. Click on the python.exe file and it should work.

This is my first post here so if its formatted incorrectly or doesn’t use the conventional terms — sorry. Let me know if the solution worked for anyone else with the problem or if I fluked it.

answered Jul 10, 2016 at 14:54

Ben Sharman's user avatar

If you kept the default settings while installing python, Your project interpreter for PyCharm will be:

C:UsersyourUserNameAppDataLocalProgramsPythonPython36python.exe

Chose the above location as your project interpreter inside PyCharm.

Depending on which python version you have, it could be either Python36python.exe or Python35python.exe.

answered Oct 15, 2016 at 14:30

Haris Ghauri's user avatar

Haris GhauriHaris Ghauri

5472 gold badges7 silver badges27 bronze badges

For me the following solution it worked:

My configuration:
Pycharm Community edition 2019.1.1
Anaconda distribution with python 3.7. Interpreter in standard location.

Problem:
Pycharm was not able to find python interpreter after reinstallation of anaconda distribution.

Solution:
— Make sure you run pycharm as admin (right click and run as admin). This was actually the critical step.
— Create new project (or open an existing one)
— Depending on the choice choose interpter or go to file > settings > project interpreter > choose small gear on rights side > add > on base interpreter choose the 3 dots > paste the location of the interpreter in the anaconda distribution.

Hope it helped someone. For me the blocking point was that for some reason pycharm was not launching with admin rights.

Blockquote

answered Oct 14, 2019 at 11:03

CVname's user avatar

CVnameCVname

3373 silver badges12 bronze badges

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

  • Системные требования
  • Как установить
  • На Windows

  • На Mac OS

  • На Linux

  • Подготовка к работе и настройка
  • Настройки интерфейса

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

  • Настройка виртуального окружения

  • Запуск скриптов в консоли
  • Отладчик (debugger) в Pycharm
  • Deploy на удаленный хост
  • Макросы
  • Полезные хоткеи и фишки
  • ТОП 7 полезных плагинов для Pycharm
  • Что делать, если PyCharm не видит модули Python?

Twitter, Pinterest, HP, Symantec, Groupon. Как думаете, что у них общего 🤔? Не сомневаюсь, ответ вам известен. Но помимо того, что это крупнейшие на мировом IT-рынке компании, есть и более специфичная деталь: те их сотрудники, кто программирует на языке Python, пишут свой код в среде разработки PyCharm.

Талантливые ребята из JetBrains разработали одну из наиболее используемых IDE в мире для этого языка программирования.

IDE PyCharm выбирают из-за его удобства, функционала, возможностей кастомизации и поддержки со стороны разработчиков.

В начале 2019 года компания JetBrains опросила почти 7000 разработчиков. 42% опрошенных, которые пишут на Python, выбрали PyCharm как основную IDE для своей работы.

Результаты опроса JetBrains по использованию IDE для работы с Python.

PyCharm кроссплатформенна и совместима с Windows, Linux и MacOS. Она поддерживает, как вторую, так и третью версию Питона и, кроме всего прочего, имеет красивый и функциональный UI.

Так выглядит интерфейс IDE PyCharm

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

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

PyCharm анализирует ваш код в фоновом режиме, подсвечивает ошибки и подсказывает варианты их исправления.

Тут реализованы системы автодополнения и контроля качества кода в соответствии со стандартом PEP8. Всё для того, чтобы сделать текст ваших программ красивее, чище и структурированнее.

В интегрированной среде от JetBrains поддерживаются основные современные Python-фреймворки для веб-разработки, в ней вы сможете работать с Jupyter-notebook, подключать Anaconda, а также прочие библиотеки для научных вычислений и Data Science. Но, как говорится — «И это ещё не всё!». Помимо, собственно, питона, PyCharm отлично ладит и с другими языками программирования — JS, TypeScript-а, SQL или шаблонизаторами.

Системные требования

Официальные системные требования последней версии PyCharm выглядят так:

ОС:

  • Windows — Microsoft Windows 10 64-битили Windows 8 64-бит;
  • macOS — macOS 10.13 или выше;
  • Linux — среда GNOME или KDE.

RAM: не менее 2 ГБ, но рекомендуется 8 ГБ;

Место на диске: установка потребует 2,5 ГБ, рекомендуется использование SSD;

Разрешение экрана: не менее 1024×768 пикселей;

Python: Python 2.7, Python 3.5 или более поздняя версия;

При этом разработчики обращают внимание пользователей macOS и Linux на то, что JBR 11 поставляется в комплекте с PyCharm, и дополнительно устанавливать Java им не нужно.

В самих системных требованиях нет ничего особенного, однако хочется отметить, что IDE прекрасно себя чувствует и на Windows 7, а к рекомендациям по поводу 8 ГБ оперативной памяти и использования SSD стоит тщательным образом прислушаться, не прогадаете 😉.

Как установить

Процесс установки вкратце описан на официальном сайте для каждой из поддерживаемых ОС:

На Windows

  1. Запускаете файл pycharm.exe.
  2. Следуете инструкциям инсталл-мастера.
  3. Выбираете нужные параметры установки.
  4. Готово.

На Mac OS

  1. Сперва следует скачать файл pycharm.dmg.
  2. Затем смонтировать диск в вашей системе.
  3. И, наконец, необходимо скопировать PyCharm в Applications.

На Linux

  1. Файл pycharm.tar.gz нужно скопировать в выбранную папку.
  2. Обязательно убедитесь, что у вас есть права доступа RW для данного каталога.
  3. Распакуйте pycharm.tar.gz используя команду: tar -xzf pycharm-2020.1.2.tar.gz
  4. Будьте внимательны: архив НЕЛЬЗЯ РАСПАКОВЫВАТЬ в папку с существующей инсталляцией.
  5. Теперь можно запустить pycharm.sh из каталога bin.

Подготовка к работе и настройка

Перед тем, как приступить к разработке в PyCharm, вам нужно создать проект, поскольку все дальнейшие манипуляции будут происходить именно в нём и на его основе.

Чтобы начать новый проект, нажмите New Project и придумайте ему имя. Теперь можно приступить к настройке.

Чтобы начать новый проект, нажмите «New Project»

Настройки интерфейса

Несмотря на то, что разработчики из JetBrains начинали свой путь в России, смена языка интерфейса в среде разработки не предусмотрена, поэтому к вашим услугам будет лишь родной язык Уильяма Шекспира.

Зато вы можете изменить сами шрифты и их размеры, пройдя по пути:

File -> Settings -> editor -> font

Поменять цветовую схему UI:

File -> Settings -> editor -> color scheme

И сконфигурировать множество других аспектов, вроде общих настроек, конфигураций прокрутки, настроек цвета для каждого доступного языка и так далее. Для всего этого есть редактор:

file -> settings -> editor

Общие настройки редактора находятся в file -> settings -> editor

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

Скачать интерпретатор вы можете с официального сайта Python. Если в ваши планы не входит работа с библиотеками, которые есть только во второй версии языка, то стоит качать последний релиз Python 3.

О том, как установить Python:

Для использования установленного интерпретатора, выберите его в настройках:

File -> Settings -> Project:<name> -> Project Interpreter

Настройка интерпретатора в Pycharm (file -> settings -> Project:<name> -> Project Interpreter)

💭 Если PyСharm не видит интерпретатор, попробуйте добавить его вручную. Для этого:

  1. Нажмите на шестеренку в верхнем правом углу, выберите «Add..«.
  2. Далее выберите «System Interpreter«;
  3. Нажмите на 3 точки «» справа от поля в выбором интерпретатора;
  4. Укажите путь до интерпретатора.

Добавление вручную нового интерпретатора в PyCharm

Настройка виртуального окружения

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

Venv — это, грубо говоря, директория, содержащая ссылку на интерпретатор и набор установленных библиотек. Виртуальное окружение “изолирует” ваши проекты, и помогает, в частности, не запутаться в разных версиях библиотек, адаптированных для каждого из них по отдельности.

Подробнее про виртуальное окружение:

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

File -> Settings -> Project:<name> -> Project Interpreter

Также в этом меню можно создать виртуальные окружения с нуля. Для этого:

  • Нажмите на шестеренку в верхнем правом углу, выберите «Add..«.
  • Выберите «Virual Enviroment» и задайте параметры.

Создание виртуального окружения средствами PyCharm ()

Venv создано и готово к работе 👌.

Окружение Pipenv создается аналогичным образом

Запуск скриптов в консоли

Чтобы запустить код в PyCharm, нужно выбрать интерпретатор в настройках (как это сделать я писал чуть выше).

Также, перед запуском своего кода в PyCharm необходимо добавить конфигурацию (чтобы IDE понимал, какой файл ему запускать и по каким правилам). Изначально, если проект новый, конфигурации нет, и кнопка запуска не активна.

В новом проекте кнопка запуска не активна, т.к конфигурации для запуска отсутствуют.

Чтобы запустить код в новом проекте, зайдите в

Run -> Run

или выполните комбинацию:

Alt + Shift + F10

Для запуска кода в PYCharm выберите

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

Диалоговое окно с выбором вариантов запуска

После запуска, откроется терминал, в котором вы увидите результат выполнения своего скрипта и сообщение о том, что процесс завершился с кодом 0 (0 означает успешное завершение).

Результат выполнения скрипта вы увидите в окне «Run», которое откроется снизу.

Далее, когда конфигурация создана и сохранена, запускать свой код на выполнения можно комбинацией:

Shift + F10

☝️ Если скрипт не запускается, возможно вы не сохранили конфигурацию или PyCharm не видит интерпретатор. Настроить или создать конфигурацию можно в меню «Edit Configurations..«, которое находится сверху справа, около кнопки «Run».

Есть еще один способ запуска кода:

  • Внизу окна программы кликните на «Terminal«.
  • Напишите в терминале python <name>.py или python3 <name>.py.

Альтернативный вариант запуска Python-кода — через встроенный терминал.

💁‍♂️ В целях обучение, вам может понадобиться быстро писать и проверять Python-инструкции. Для этого в PyCharm-е реализован интерактивный режим (по аналогии с IDLE). Чтобы его вызвать, достаточно нажать на «Python Console» внизу слева.

PyCharm умеет запускать Python-код в интерактивном режиме

Отладчик (debugger) в Pycharm

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

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

Для старта отладки, нужно поставить так называемую точку останова. Это красный кружок напротив строки кода.

Для отладки кода выберите точку останова (красный кружок напротив нужной строки)

Вы можете установить её где захотите, но чаще всего точку следует ставить там, где интерпретатор увидел ошибку.

Для запуска кода в режиме отладки нажмите на значок в «жука» в левом верхнем углу:

Значок «зеленый жук» запустит код в режиме отладки

Или выполните комбинацию:

Shift + F9

Отладка началась.

Запустив код в режиме отладки, откроется окно «Debug» с информацией о ходе выполнения и текущем состоянии.

Теперь, нажимая F8, можно последовательно шагать по строчкам кода и смотреть текущее состояние всей программы.

«Шагать» можно и через F7, но в таком случае дебаггер будет совершать «Шаг с заходом». Т.е. при встрече вызова функции он будет заходить в её описание и последовательно проходить по инструкциям.

Все варианты навигации в режиме отладки можно посмотреть в окне «Debugger»:

Кнопки навигации в режиме отладки в PyCharm

Для каждой кнопки существует свой hotkey — чтобы увидеть его, достаточно навести курсор на нужную кнопку.

Deploy на удаленный хост

Развернуть и отправить код на сервер возможно прямиком из PyCharm.

Инструмент не доступен в бесплатной комьюнити-версии

Чтобы добавить удалённый сервер, первым делом перейдём в:

Tools -> Deployment -> Configuration

Здесь сначала вводим имя, а затем настраиваем данные сервера. Потом вводим имя и пароль пользователя и проверяем соединение при помощи кнопки Test Connection.

Для проверки соединения с удаленным хостом нажмите «Test Connection».

Переключаемся на следующую вкладку под названием Mappings. Мапы здесь — это соответствия между путями на вашем компьютере и путями на сервере. Производим и применяем настройки.

Во вкладке Mapping — соответствия между путями на вашем компьютере и путями на сервере.

Теперь можно производить deploy:

Tools -> Deployment -> Upload to <your_host_name>

💡 Лайфхак: для удобной работы можно настроить автоматический деплой на удаленный сервер после каждого «сохранения». Для этого перейдите в Tools -> Deployment -> Options и выберите On explicit save action (Ctrl + S).

Автоматический deploy на сервер по умолчанию в IDE PyCharm

Макросы

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

Чтобы создать или настроить свой собственный макрос, вам нужно выбрать:

Edit -> Macros -> Start Macro Recording

После записи макроса, нажмите Stop Macro Recording.

Полезные хоткеи и фишки

Как поменять цвет консоли в pycharm.
Поменять цвет консольного бэкграунда или шрифтов предельно просто: для этого нужно всего лишь зайти в настройки цветовой схемы и изменить их так, как того пожелает ваш внутренний дизайнер:

File -> Settings -> Editor -> Color Scheme

Поиск по всему проекту.

  • Для поиска по коду во всем проекта, выполните комбинацию Ctrl + Shift + F.
  • Для поиска всего и вся во всём проекте дважды нажимаем клавишу Shift.

Хоткеи по запуску и дебаггингу.
С помощью комбинации клавиш
Shift + F10 можно запустить ваш проект, а нажав Shift + F9 — начать его отладку.

Закомментировать сразу несколько строк.
Комментирование кода ещё никогда не было таким простым: вы мышкой выделяете нужные строки, а затем нажимаете
Ctrl + /.

Повторив то же самое действие на том же самом месте, вы выполните раскомментирование кода.

Отступы.

  • Отступ — Tab.
  • Для нескольких строк выделите нужные строки и нажмите Tab.
  • Для обратного отступа (отступа в левую сторону) — Shift + Tab.

Некоторые горячие клавиши.

  • Ctrl + Alt + L — автоформатирование кода по PEP 8.
  • Ctr + Z — отмена последнего выполненного действия.
  • Ctr + Up/Down — прокрутка без изменения позиции курсора.
  • Ctr + D — дублировать строку.
  • Tab / Shift + Tab — увеличить / уменьшить отступ.
  • Ctr + Space — выводит предложения по автозаполнению.

Тут шпаргалка по хоткеям в Pycharm.

ТОП 7 полезных плагинов для Pycharm

Меню установки плагинов находится в:

File -> Settings -> Plugins

Для установки плагина достаточно написать его название в строке поиска, найти плагин и нажать «Install«.

⭐ Вот список полезных плагинов, которые стоит установить:

  • Highlight Bracket Pair (описание) — плагин позволяет не запутаться в излюбленном занятии программистов — поиске соответствия между открывающими и закрывающими скобками.
  • Grep Console (описание) — расширение функционала стандартной консоли PyCharm — изменение цвета для разного типа сообщений, вкладки в консоли, аналог grep для вывода и т.д.
  • Pylint (описание) — Python линтер. После установки появится меню «Pylint» в нижнем левом углу. Для работы плагина необходимо установить модуль pylint (python -m pip install pylint или python3 -m pip install pylint), и в настройках PyCharm указать путь до него (в Windows он обычно лежит в папке C:<python_path>Scripts, а в Linux путь до pylint можно узнать с помощью which pylint).
  • DeepBugs for Python — ищет потенциальные баги и проблемы, связанные с качеством кода используя модели машинного обучения.

Другие полезные плагины:

  • Python Smart Execute (описание) — комбинация Alt + Shift + A копирует выделенный код в Python-консоль и выполняет его.
  • MyPy (описание) — плагин для проверки типов (type hinting) и анализатор исходного кода для Python. После установки появится меню «MyPy» в нижнем левом углу.
  • CodeGlance (описание) — добавляет мини-карту (minimap) кода в окне редактора справа.

Что делать, если PyCharm не видит модули Python?

Если у вас возникла подобная проблема, то в первую очередь стоит проверить настройки интерпретатора.

Вариант №1 — сброс настроек и выборе новой версии интерпретатора. Настройки находятся тут:

Settings -> Project:<project_name> -> Project Interpreter

Вариант №2 — По умолчанию PyCharm ищет модули начиная от корня проекта. Подскажите PyCharm, где находится директория с вашими модулями. Для этого в проводнике слева щелкните по директории (правой кнопкой мыши), и в контекстном меню выберите Mark Directory As -> Sources Root.

This article will tell you how to install a python interpreter in the PyCharm project. Before start, you should make sure you had installed python on your system.

1. How To Install Python Interpreter In PyCharm.

1.1 On macOS.

  1. Open PyCharm IDE, I use PyCharm community edition with Anaconda plugin.
  2. Then click the PyCharm —> Preferences… menu item ( macOS) or Window —> Preferences menu item ( Windows OS ).
  3. In the popup Preferences window, click Project: Project-Name —> Project Interpreter menu item at the left panel. Then you can see there is no Project Interpreter that has been selected on the right panel.
  4. Click the Project Interpreter drop-down list on the right panel, then click Show All… item, it will pop up the Project Interpreters dialog window.
  5. There is a default PyCharm python interpreter in the dialog. You can select it as the project python interpreter.
  6. If you want to install another Python interpreter, you can click the plus button ( + ) at the bottom left corner of the Project Interpreters popup dialog window.
  7. Then it will popup Add Python Interpreter window. There list 4 types of python interpreters on the window left side, they are Virtualenv Environment, Conda Environment, System Interpreter, Pipenv Environment. You can select the python interpreter type from the left pane as you need.
  8. After you select one python interpreter in PyCharm, it will list all the modules package and version information that has been installed in that interpreter in the Preferences window, you can code and run your python program with that python interpreter.

1.2 On Windows.

  1. It is similar to macOS, the difference is that you should click the PyCharm File —> Settings… menu item to open the Settings dialog.
  2. The Settings dialog is the same as the Preferences dialog on macOS.
  3. Now you can follow steps 3 – 8 of section 1.1 On macOS to install the Python interpreter.

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти длину дуги окружности в сантиметрах
  • Как найти айфон если нет приложения
  • Как найти конечную координату тела
  • Сталкер чистое небо как найти папку gamedata
  • Как найти периметр прямоугольника 2 класс математика

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии