I have two pure python projects in PyCharm 3.4.1 Professional Edition. The first one, let’s call it p
(like package), is structured as a setuptools package (i.e. with setup.py, all requirements etc., however it is not uploaded to pypi or any other online repository). The second one, let’s call it s
(like script), is just a python script along with two modules.
Project s
is (in PyCharm) configured to use a dedicated virtualenv, let’s call it venv
.
The problem I have is the following: when I install the project (package) p
in venv
like this:
$ source /path/to/venv/bin/activate
(venv)$ cd /path/to/p
(venv)$ python3 setup.py develop
in PyCharm in project s
, import p
statements are errorneous with message No module named p. However, when I run the script in s
, everything is fine, the only problem is the PyCharm IDE complaining about not being able to find the module. I can live with this but it is very annoying…
Why does this happen? Is it a PyCharm thing or packaging related thing? See NEWS below.
The project/package p
has the following structure:
p/
|
+- p/
| |
| +- __init__.py
| +- other subpackages, modules, etc.
+- setup.py
+- README, DESCRIPTION, setup.cfg, etc.
When I configure the PyCharm project p
to live in its own virtualenv and install it there in development mode, everything works fine.
NEWS
This problem is still present in PyCharm 5.0.4. However, I managed to solve it, kind-of.
For some reasons I had to install another package from pypi. I did it through PyCharm by going to File -> Settings -> Project: -> Project Interpreter, there clicking on the green +
, finding the package and pressing the Install Package button. After the installation, the package installed by python3 setup.py develop
is well recognized by PyCharm. Obviously the problem was that PyCharm didn’t have some cache in sync with reality.
So the new question is, can PyCharm be told to update its caches regarding the used python environment?
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.
15:49:29|mymac [~]:pip install requests
Requirement already satisfied (use --upgrade to upgrade): requests in /opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages
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
38.3k9 gold badges50 silver badges89 bronze badges
asked Jul 5, 2015 at 21:56
1
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 other thing that won’t hurt to do is select «Associate this virtual environment with the current project», in the interpreter’s edit box.
Gulzar
23.7k27 gold badges116 silver badges205 bronze badges
answered Jan 6, 2019 at 7:50
Todor MinakovTodor Minakov
19.2k3 gold badges55 silver badges60 bronze badges
5
If you are using PyCharms CE (Community Edition), then click on:
File->Default Settings->Project Interpreter
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.
Gulzar
23.7k27 gold badges116 silver badges205 bronze badges
answered Mar 3, 2017 at 1:04
user7650698user7650698
5374 silver badges2 bronze badges
2
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:
Go to
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:
$ pip show gym
Name: gym
Version: 0.13.0
Summary: The OpenAI Gym: A toolkit for developing and comparing your reinforcement learning agents.
Home-page: https://github.com/openai/gym
Author: OpenAI
Author-email: gym@openai.com
License: UNKNOWN
Location: /usr/local/lib/python3.7/site-packages
...
Add the path specified under Location to the interpreter paths, here
/usr/local/lib/python3.7/site-packages
Then, let indexing finish and perhaps additionally reopen your project.
answered Jun 8, 2020 at 16:19
whiletruewhiletrue
10.5k6 gold badges27 silver badges47 bronze badges
3
Open python console of your pyCharm. Click on Rerun.
It will say something like following on the very first line
/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Applications/PyCharm.app/Contents/helpers/pydev/pydevconsole.py 52631 52632
in this scenario pyCharm is using following interpretor
/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
Now fire up console and run following command
sudo /System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 -m pip install <name of the package>
This should install your package
answered Jun 1, 2016 at 18:22
0
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).
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!
answered Sep 18, 2017 at 17:37
NightFuryNightFury
13.4k6 gold badges71 silver badges120 bronze badges
0
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.
Try this:
pip3 install requests
answered Mar 25, 2016 at 13:48
insecure-ITinsecure-IT
2,0784 gold badges18 silver badges26 bronze badges
2
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.
answered Jul 19, 2019 at 6:52
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:
include-system-site-packages = false
to:
include-system-site-packages = true
answered Nov 18, 2021 at 16:42
David LopezDavid Lopez
3634 silver badges13 bronze badges
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 1st in ${PATH}, 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):
import os
import sys
print("Executable:", sys.executable)
print("Version:", sys.version)
print("CWD:", os.getcwd())
print("UName:", getattr(os, "uname", lambda: None)())
for evn in ("PATH", "PYTHONHOME", "PYTHONPATH"):
print("{:s}: {:}".format(evn, os.environ.get(evn)))
print("sys.path:", sys.path)
2. Python‘s module search mechanism misunderstanding
-
According to [Python.Docs]: Modules — The Module Search Path:
When a module named spam is imported, the interpreter first searches for a built-in module with that name. These module names are listed in sys.builtin_module_names. If not found, it then searches for a file named
spam.py
in a list of directories given by the variable sys.path. sys.path is initialized from these locations:-
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 ${PYTHONPATH}. 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 ${PYTHONPATH}) the module would be missing, yielding lots of headaches
-
-
A somewhat related scenario: [SO]: ModuleNotFoundError: No module named ‘cryptography.hazmat’; ‘cryptography’ is not a package (@CristiFati’s answer)
-
For a fix, check [SO]: How PyCharm imports differently than system command prompt (Windows) (@CristiFati’s answer)
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
-
Possible fixes:
-
Restart PyCharm
-
Restart the machine
-
Recreate the project (remove the .idea dir from the project)
-
Reset PyCharm settings: from menu select File -> Manage IDE Settings -> Restore Default Settings…. Check [JetBrains]: Configuring PyCharm settings or [JetBrains.IntelliJ-Support]: Changing IDE default directories used for config, plugins, and caches storage for more details
-
Reinstall PyCharm
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
-
Not directly related to the question, but posting:
-
[SO]: Run / Debug a Django application’s UnitTests from the mouse right click context menu in PyCharm Community Edition? (a PyCharm related investigation from a while ago)
-
[SO]: ImportError: No module named win32com.client (@CristiFati’s answer)
answered Aug 15, 2022 at 16:07
CristiFatiCristiFati
38.3k9 gold badges50 silver badges89 bronze badges
-
If you go to
pycharm
project interpreter -> clicked on one of the installed packages then hover -> you will see wherepycharm
is installing the packages. This is where you are supposed to have your package installed. -
Now if you did
sudo -H pip3 install <package>
pip3 installs it to different directory which is/usr/local/lib/site-packages
since it is different directory from what pycharm
knows hence your package is not showing in pycharm
.
Solution: just install the package using pycharm
by going to File->Settings->Project->Project Interpreter -> click on (+) and search the package you want to install and just click ok.
-> you will be prompted package successfully installed and you will see it pycharm
.
Pingolin
3,1616 gold badges25 silver badges40 bronze badges
answered Apr 16, 2019 at 14:43
2
If any one faces the same problem that he/she installs the python packages but the PyCharm IDE doesn’t shows these packages then following the following steps:
- Go to the project in the left side of the PyCharm IDE then
- Click on the venv library then
- Open the pyvenv.cfg file in any editor then
- Change this piece of code (include-system-site-packages = flase) from false to true
- Then save it and close it and also close then pycharm then
- Open PyCharm again and your problem is solved.
Thanks
answered Jul 24, 2022 at 8:47
This did my head in as well, and turns out, the only thing I needed to do is RESTART Pycharm. Sometimes after you’ve installed the pip, you can’t load it into your project, even if the pip shows as installed in your Settings. Bummer.
answered Jun 24, 2020 at 11:33
For Anaconda:
Start Anaconda Navigator -> Enviroments -> «Your_Enviroment» -> Update Index -> Restart IDE.
Solved it for me.
answered Aug 6, 2021 at 21:23
AndreasAndreas
8,7143 gold badges15 silver badges38 bronze badges
After pip installing everything I needed. I went to the interpreter and re-pointed it back to where it was at already.
My case: python3.6 in /anaconda3/bin/python using virtualenv…
Additionally, before I hit the plus «+» sign to install a new package. I had to deselect the conda icon to the right of it. Seems like it would be the opposite, but only then did it recognize the packages I had/needed via query.
answered Feb 1, 2019 at 19:42
In my case the packages were installed via setup.py + easy_install, and the they ends up in *.egg directories in site_package dir, which can be recognized by python but not pycharm.
I removed them all then reinstalled with pip install and it works after that, luckily the project I was working on came up with a requirements.txt file, so the command for it was:
pip install -r ./requirement.txt
answered Jul 8, 2019 at 10:32
RipleyRipley
6641 gold badge6 silver badges16 bronze badges
I just ran into this issue in a brand new install/project, but I’m using the Python plugin for IntelliJ IDEA. It’s essentially the same as PyCharm but the project settings are a little different. For me, the project was pointing to the right Python virtual environment but not even built-in modules were being recognized.
It turns out the SDK classpath was empty. I added paths for venv/lib/python3.8 and venv/lib/python3.8/site-packages and the issue was resolved. File->Project Structure and under Platform Settings, click SDKs, select your Python SDK, and make sure the class paths are there.
answered May 22, 2020 at 16:58
Dave WolfeDave Wolfe
6605 silver badges14 bronze badges
pip install --user discord
above command solves my problem, just use the «—user» flag
answered Feb 26, 2022 at 17:08
Siddy HacksSiddy Hacks
1,85614 silver badges15 bronze badges
I fixed my particular issue by installing directly to the interpreter. Go to settings and hit the «+» below the in-use interpreter then search for the package and install. I believe I’m having the issue in the first place because I didn’t set up with my interpreter correctly with my venv (not exactly sure, but this fixed it).
I was having issues with djangorestframework-simplejwt because it was the first package I hadn’t installed to this interpreter from previous projects before starting the current one, but should work for any other package that isn’t showing as imported. To reiterate though I think this is a workaround that doesn’t solve the setup issue causing this.
answered Jul 6, 2022 at 7:15
—WINDOWS—
if using Pycharm GUI package installer works fine for installing packages for your virtual environment but you cannot do the same in the terminal,
this is because you did not setup virtual env in your terminal, instead, your terminal uses Power Shell which doesn’t use your virtual env
there should be (venv) before you’re command line as shown instead of (PS)
if you have (PS), this means your terminal is using Power Shell instead of cmd
to fix this, click on the down arrow and select the command prompt
select command prompt
now you will get (venv) and just type pip install #package name# and the package will be added to your virtual environment
answered Sep 17, 2022 at 20:54
I tried all the answers but non of them worked!
«»IF YOU ARE LAZY!! Temporary Answer is : «»
you should consider finding the path PyCharm is really installing libraries via pip in terminal and add that to your project like in the next pictures!
1_ go to interpreter settings :
2_ click on «Show All» :
3_ find your current projects interpreter and click on show Paths for selected interpreter :
4_ Now try adding different paths that you think might pip be installing libraries to and it adds all the libraries from that path to your new project :
answered Jun 23 at 19:44
On windows I had to cd into the venv folder and then cd into the scripts folder, then pip install module started to work
cd venv
cd scripts
pip install module
answered Nov 24, 2019 at 9:36
instead of running pip install in the terminal -> local use terminal -> command prompt
see below image
pycharm_command_prompt_image
vimuth
5,09434 gold badges79 silver badges116 bronze badges
answered Aug 14, 2022 at 3:34
In your pycharm terminal run pip/pip3 install package_name
answered Nov 17, 2020 at 17:42
AnubhavAnubhav
1,98422 silver badges17 bronze badges
Введение При работе с Python и его средой разработки PyCharm, новички часто сталкиваются с проблемой «Unresolved reference». Это сообщение об ошибке говорит о
Введение
При работе с Python и его средой разработки PyCharm, новички часто сталкиваются с проблемой «Unresolved reference». Это сообщение об ошибке говорит о том, что PyCharm не может найти определенный модуль или ссылку на него. Рассмотрим типичный пример.
Представим, что у нас есть следующая структура каталогов:
.
├── main.py
├── helpers
│ ├── helper.py
В main.py
мы пытаемся импортировать функции из helper.py
следующим образом:
from helpers.helper import some_function
Но PyCharm выдает ошибку «Unresolved reference» и не может найти модуль helpers.helper
.
Причина проблемы
В большинстве случаев причина ошибки «Unresolved reference» заключается в том, что PyCharm не может определить путь к модулю, который вы пытаетесь импортировать. Это может произойти, если модуль находится в другом каталоге, и PyCharm не знает, где искать этот каталог.
Решение проблемы
Чтобы решить эту проблему, необходимо сделать так, чтобы PyCharm знал, где искать модули для импорта. Для этого нужно добавить нужный каталог в системный путь Python.
В Python пути к модулям хранятся в переменной sys.path
. Это список строк, каждая из которых представляет собой путь к каталогу. Когда Python пытается импортировать модуль, он ищет его в этих каталогах.
Чтобы добавить каталог в sys.path
, можно использовать функцию sys.path.append()
. Например, если мы хотим добавить каталог helpers
в sys.path
, мы можем сделать это следующим образом:
import sys sys.path.append("/path/to/helpers") from helpers.helper import some_function
Заключение
В этой статье мы рассмотрели, как решить проблему «Unresolved reference» в PyCharm. Эта проблема часто возникает у новичков, и ее решение поможет понять, как работает импорт модулей в Python и как управлять путями к модулям.
Не понимаю, почему pycharm не видит библиотеки при импорте, хоть их установка через консоль проходит успешно. Допустим, я устанавливаю библиотеку speech_recognition через терминал(используя pip), установка проходит успешно, но при попытке импортировать библиотеку, появляется ошибка: «ModuleNotFoundError: No module named ‘speech_recognition'». После я устанавливаю эту библиотеку через менеджер пакетов, теперь ее видно, но не хватает библиотеки pyAudio. При установке pyAudio через консоль, библиотеки также не видно, а при установке pyAudio через менеджер появляется ошибка, связанная именно с самим пакетом. И по такой же схеме со всеми библиотеками, только названия меняются, поэтому не могу с ними работать, что мне делать?
-
Вопрос задан
-
11350 просмотров
Introduction
There could be a few reasons why you might get a «module not found» error in PyCharm even though the module is installed, and there is no typo in the spelling of the name of the module which is being imported.
Why does «Module Not Found Error» error occurs in Pycharm
What Pycharm does is that while creating a new project, it by default creates a new virtual environment, without even inheriting the globally installed packages. Thus, we will be getting a «Module Not Found Error» even after the module is installed globally.
There are various ways by which we can get rid of the above problem, which we will be seeing just now .
import my_module
# Some code here
Below is the error which we get upon running above code.
Traceback (most recent call last):
File "/path/to/your/file.py", line 1, in <module>
import my_module
ModuleNotFoundError: No module named 'my_module'
How to Resolve «Module Not Found Error» ?
Method 1
Creating a new project by clicking on File -> New Project-> Previously Configured Interpreter.This will create a new Python project with the same version and packages as the globally installed one, and thus, if a module is installed globally we will be able to use it with Pycharm .
Method 2
Another way is to install the missing package for that virtual environment, and we can do that by simply going through File -> Settings -> Project -> Python Interpreter . After which we will get to see this kind of prompt.
After which click on ‘+’, then search for the module which we desire in the available packages-> clicking on the install.This will install the required package and you will be able to use it with your code in Pycharm. If even after this it didn’t resolve, you can try restarting your Pycharm, it will definitely work.
Method 3
Another work around can be to change the Python Interpreter which we are using for our virtual environment to the python interpreter used inside the console. We can change the python version by typing the below command
python - -version
It will show the python version installed and we should change it to this python interpreter.
We can do this by going through File -> Settings -> Project -> Python Interpreter -> Selecting a different interpreter from the drop down -> Clicking OK.
Our Project will start using that Python Interpreter and our error will be gone.
Method 4
There may be some other ways which may occur resulting in «ModuleNotFoundError» which are not related to Pycharm like, there can be a typo in the module name. Make sure that you’ve spelled the module name correctly.
Conclusion:-
Hope, this would help you in getting rid of your problem of «Module Not Found Error» in Pycharm without much of an effort.