Почему pycharm не видит модули

от admin

PyCharm doesn't recognize installed module

I’m having trouble with using ‘requests’ module on my Mac. I use python34 and I installed ‘requests’ module via pip. I can verify this via running installation again and it’ll show me that module is already installed.

Although I can import ‘requests’ module via interactive Python interpreter, trying to execute ‘import requests’ in PyCharm yields error ‘No module named requests’. I checked my PyCharm Python interpreter settings and (I believe) it’s set to same python34 as used in my environment. However, I can’t see ‘requests’ module listed in PyCharm either.

It’s obvious that I’m missing something here. Can you guys advise where should I look or what should I fix in order to get this module working? I was living under impression that when I install module via pip in my environment, PyCharm will detect these changes. However, it seems something is broken on my side .

CristiFati's user avatar

Martinecko's user avatar

23 Answers 23

In my case, using a pre-existing virtualenv did not work in the editor — all modules were marked as unresolved reference (running naturally works, as this is outside of the editor’s config, just running an external process (not so easy for debugging)).
Turns out PyCharm did not add the site-packages directory. the fix is to manually add it.

On Pycharm professional 2022.3

Open File -> Settings -> Python Interpreter, open the drop-down and pick "Show All. " (to edit the config) (1), right click your interpreter (2), click "Show Interpreter Paths" (3).

In that screen, manually add the "site-packages" directory of the virtual environment [looks like . /venv/lib/python3.8/site-packages (4) (I’ve added the "Lib" also, for a good measure); once done and saved, they will turn up in the interpreter paths.

the steps

The other thing that won’t hurt to do is select "Associate this virtual environment with the current project", in the interpreter’s edit box.

Todor Minakov's user avatar

If you are using PyCharms CE (Community Edition), then click on:

File->Default Settings->Project Interpreter

Screenshot: Interpretor Settings

See the + sign at the bottom, click on it. It will open another dialog with a host of modules available. Select your package (e.g. requests) and PyCharm will do the rest.

This issue arises when the package you’re using was installed outside of the environment (Anaconda or virtualenv, for example). In order to have PyCharm recognize packages installed outside of your particular environment, execute the following steps:

Preferences -> Project -> Project Interpreter -> 3 dots -> Show All -> Select relevant interpreter -> click on tree icon Show paths for the selected interpreter

Now check what paths are available and add the path that points to the package installation directory outside of your environment to the interpreter paths.

To find a package location use:

Add the path specified under Location to the interpreter paths, here

Then, let indexing finish and perhaps additionally reopen your project.

whiletrue's user avatar

Open python console of your pyCharm. Click on Rerun. It will say something like following on the very first line

in this scenario pyCharm is using following interpretor

Now fire up console and run following command

This should install your package 🙂

Pycharm is unable to recognize installed local modules, since python interpreter selected is wrong. It should be the one, where your pip packages are installed i.e. virtual environment.

I had installed packages via pip in Windows. In Pycharm, they were neither detected nor any other Python interpreter was being shown (only python 3.6 is installed on my system).

enter image description here

I restarted the IDE. Now I was able to see python interpreter created in my virtual environment. Select that python interpreter and all your packages will be shown and detected. Enjoy!

enter image description here

NightFury's user avatar

Using dual python 2.7 and 3.4 with 2.7 as default, I’ve always used pip3 to install modules for the 3.4 interpreter, and pip to install modules for the 2.7 interpreter.

pip3 install requests

insecure-IT's user avatar

This is because you have not selected two options while creating your project:- ** inherit global site packages ** make available to all projects Now you need to create a new project and don’t forget to tick these two options while selecting project interpreter.

The solution is easy (PyCharm 2021.2.3 Community Edition). I’m on Windows but the user interface should be the same. In the project tree, open External libraries > Python interpreter > venv > pyvenv.cfg. Then change:

PyCharm image

David Lopez's user avatar

Before going further, I want to point out how to configure a Python interpreter in PyCharm:
[SO]: How to install Python using the "embeddable zip file" (@CristiFati’s answer). Although the question is for Win, and has some particularities, configuring PyCharm is generic enough and should apply to any situation (with minor changes).

There are multiple possible reasons for this behavior.

1. Python instance mismatch

Happens when there are multiple Python instances (installed, VEnvs, Conda, custom built, . ) on a machine. Users think they’re using one particular instance (with a set of properties (installed packages)), but in fact they are using another (with different properties), hence the confusion. It’s harder to figure out things when the 2 instances have the same version (and somehow similar locations)

Happens mostly due to environmental configuration (whichever path comes 1 st in $ , aliases (on Nix), . )

It’s not PyCharm specific (meaning that it’s more generic, also happens outside it), but a typical PyCharm related example is different console interpreter and project interpreter, leading to confusion

The fix is to specify full paths (and pay attention to them) when using tools like Python, PIP, . Check [SO]: How to install a package for a specific Python version on Windows 10? (@CristiFati’s answer) for more details

This is precisely the reason why this question exists. There are 2 Python versions involved:

Project interpreter: /Library/Frameworks/Python.framework/Versions/3.4

Interpreter having the Requests module: /opt/local/Library/Frameworks/Python.framework/Versions/3.4

well, assuming the 2 paths are not somehow related (SymLinked), but in latest OSX versions that I had the chance to check (Catalina, Big Sur, Monterey) this doesn’t happen (by default)

When dealing with this kind of error, it always helps (most likely) displaying the following information (in a script or interpreter console):

2. Python‘s module search mechanism misunderstanding

  • The directory containing the input script (or the current directory when no file is specified).

  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).

  • The installation-dependent default (by convention including a site-packages directory, handled by the site module).

A module might be located in the current dir, or its path might be added to $ . That could trick users into making them believe that the module is actually installed in the current Python instance (‘s site-packages). But, when running the current Python instance from a different dir (or with different $ ) the module would be missing, yielding lots of headaches

3. A PyCharm bug

Not very likely, but it could happen. An example (not related to this question): [SO]: PyCharm 2019.2 not showing Traceback on Exception (@CristiFati’s answer)

To fix, follow one of the options from the above URL

4. A glitch

Not likely, but mentioning anyway. Due to some cause (e.g.: HW / SW failure), the system ended up in an inconsistent state, yielding all kinds of strange behaviors

Restart the machine

Recreate the project (remove the .idea dir from the project)

Needless to say that the last 2 options should only be attempted as a last resort, and only by experts, as they might mess up other projects and not even fix the problem

PyCharm не распознает модули, установленные в режиме разработки

У меня есть два чистых проекта python в PyCharm 3.4.1 Professional Edition. Первый, позвоните ему p (например, пакет), структурирован как пакет setuptools (т.е. С setup.py, все требования и т.д., Однако он не загружается в pypi или в любой другой онлайн-репозиторий). Второй, позвольте ему s (например, script), является всего лишь python script вместе с двумя модулями.

Проект s — это (в PyCharm), настроенный на использование выделенного virtualenv, позвоните ему venv .

Проблема заключается в следующем: когда я устанавливаю проект (пакет) p в venv следующим образом:

в командах PyCharm в проекте s , import p ошибочны с сообщением. Нет модуля с именем p. Однако, когда я запускаю script в s , все в порядке, единственная проблема заключается в том, что IDE PyCharm жалуется на невозможность найти модуль. Я могу жить с этим, но это очень раздражает.

Почему это происходит? Это вещь, связанная с PyCharm или с упаковкой? См. НОВОСТИ ниже.

Проект/пакет p имеет следующую структуру:

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

Новости

Эта проблема все еще присутствует в PyCharm 5.0.4. Однако мне удалось решить эту проблему.

По некоторым причинам мне пришлось установить еще один пакет из pypi. Я сделал это через PyCharm, выбрав File → Settings → Project: → Project Interpreter, нажав зеленую кнопку + , найдя пакет и нажав кнопку Install Package. После установки пакет, установленный python3 setup.py develop , хорошо известен PyCharm. Очевидно, проблема заключалась в том, что PyCharm не синхронизировал кеш с реальностью.

Итак, новый вопрос: может ли PyCharm сказать обновить свои кеши относительно используемой среды python?

PyCharm не видит стандартных модулей

Здраствуйте. Ситуация такая. Pycharm не видит стандартные библиотеки (в данном случае — библиотеку random, на первой картинке). Версия Community Edition 2018.3.3 x64. Пробовал советы из вопроса (pycharm не видит стандартные модули), но удаление/переименование папки config (которая на второй картинке, возможно, просто удалил не ту) результатов не дало, а нажав на шестерёнку, add local я не нашёл (на третьей картинке, на четвёртой — что при переходе через шестерёнку). Также почитал этот совет (PyCharm и стандартные модули), но у меня, вроде бы, уже стоит venv.

P.S. Я совсем новичок, буду благодарен, если ответите как можно понятнее. Спасибо 🙂

введите сюда описание изображения

введите сюда описание изображения

введите сюда описание изображения

введите сюда описание изображения

Ответы (1 шт):

Наведите мышь на import и прочтите сообщение об ошибке:

Подразумевается что random не используется нигде в данном скрипте. Попробуйте использовать модуль ниже — серая подсветка должна пропасть.

Когда PyCharm не видит модуль, то подсвечивает импорт красным. Сообщение в данном случае будет «no module named . «.

Python-сообщество

Добрый день, уважаемые программисты.
Работаю в PyCarm.
Не знаю, в чём проблема, в нём или во мне, но среда не желает видеть модули. Даже если используемый модуль лежит в той же папке, что и тот, который хочу импортировать.

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

Сказать, что неудобно, это ничего не сказать .
Это вообще нормально? Так должно быть или это уже проблема? Если второй вариант, то как же решить эту самую проблему?
Заранее спасибо за ответ!

Читать:
Как сделать ютуб на весь экран

Похожие статьи