简体   繁体   English

PyCharm 中未解决的参考问题

[英]Unresolved reference issue in PyCharm

I have a directory structure我有一个目录结构

├── simulate.py
├── src
│   ├── networkAlgorithm.py
│   ├── ...

And I can access the.network module with sys.path.insert() .我可以使用sys.path.insert()访问 .network 模块。

import sys
import os.path
sys.path.insert(0, "./src")
from networkAlgorithm import *

However, pycharm complains that it cannot access the module.但是,pycharm 抱怨它无法访问该模块。 How can I teach pycham to resolve the reference?我如何教pycham解析引用?

在此处输入图像描述

Manually adding it as you have done is indeed one way of doing this, but there is a simpler method, and that is by simply telling pycharm that you want to add the src folder as a source root, and then adding the sources root to your python path.手动添加确实是这样做的一种方法,但是有一种更简单的方法,那就是简单地告诉 pycharm 你想将src文件夹添加为源根目录,然后将源根目录添加到你的蟒蛇路径。

This way, you don't have to hard code things into your interpreter's settings:这样,您不必将内容硬编码到解释器的设置中:

  • Add src as a source content root:添加src作为源内容根:

在此处输入图像描述

  • Then make sure to add add sources to your PYTHONPATH under:然后确保将添加源添加到您的PYTHONPATH下:

     Preferences ~ Build, Execution, Deployment ~ Console ~ Python Console

在此处输入图像描述

  • Now imports will be resolved:现在将解决导入问题:

在此处输入图像描述

This way, you can add whatever you want as a source root, and things will simply work.这样,您可以添加任何您想要的源根目录,一切都会简单地工作。 If you unmarked it as a source root however, you will get an error:但是,如果您将其取消标记为源根目录,则会收到错误消息:

在此处输入图像描述

After all this don't forget to restart.毕竟这不要忘记重新启动。 In PyCharm menu select: File --> Invalidate Caches / Restart在 PyCharm 菜单中选择:File --> Invalidate Caches / Restart

  1. check for __init__.py file in src folder检查src文件夹中的__init__.py文件
  2. add the src folder as a source rootsrc文件夹添加为源根目录
  3. Then make sure to add sources to your PYTHONPATH (see above)然后确保将源添加到您的PYTHONPATH (见上文)
  4. in PyCharm menu select: File --> Invalidate Caches --> Restart在 PyCharm 菜单中选择:File --> Invalidate Caches --> Restart

If anyone is still looking at this, the accepted answer still works for PyCharm 2016.3 when I tried it.如果有人还在看这个,那么当我尝试它时,接受的答案仍然适用于 PyCharm 2016.3。 The UI might have changed, but the options are still the same. UI 可能已更改,但选项仍然相同。

ie. IE。 Right click on your root folder --> 'Mark Directory As' --> Source Root右键单击您的根文件夹 --> 'Mark Directory As' --> 源根目录

After testing all workarounds, i suggest you to take a look at Settings -> Project -> project dependencies and re-arrange them.在测试了所有解决方法后,我建议您查看Settings -> Project -> project dependencies项并重新安排它们。

pycharm 偏好

Normally, $PYTHONPATH is used to teach python interpreter to find necessary modules .通常, $PYTHONPATH 用于教 python 解释器找到必要的模块 PyCharm needs to add the path in Preference. PyCharm 需要在 Preference 中添加路径。

在此处输入图像描述

There are several reasons why this could be happening.发生这种情况有几个原因。 Below are several steps that fixes the majority of those cases:以下是解决大多数情况的几个步骤:

.idea caching issue .idea 缓存问题

Some .idea issue causing the IDE to show error while the code still runs correctly.一些.idea问题导致 IDE 在代码仍然正常运行时显示错误。 Solution:解决方案:

  1. close the project and quick PyCharm关闭项目并快速使用 PyCharm
  2. delete the .idea folder where the project is.删除项目所在的.idea文件夹。 note that it is a hidden folder and you might not be aware of its existence in your project directory.请注意,它是一个隐藏文件夹,您可能不知道它存在于您的项目目录中。
  3. start PyCharm and recreate the project启动 PyCharm 并重新创建项目

imports relative not to project folder相对于项目文件夹的导入

Relative imports while code root folder is not the same as the project folder.代码根文件夹与项目文件夹不同时的相对导入。 Solution:解决方案:

  1. Find the folder that relative imports require in the project explorer在项目资源管理器中找到相对导入所需的文件夹
  2. right click and mark it as "Source Root"右键单击并将其标记为“源根”

Editor not marking init .py as Python but as Text编辑器没有将init .py 标记为 Python,而是标记为 Text

Which is the most illusive of all the cases.这是所有案例中最虚幻的。 Here, for some reason, PyCharm considers all __init__.py files not to be python files, and thus ignores them during code analysis.在这里,出于某种原因,PyCharm 认为所有__init__.py文件都不是 python 文件,因此在代码分析期间会忽略它们。 To fix this:要解决这个问题:

  1. Open PyCharm settings打开 PyCharm 设置
  2. Navigate to Editor -> File Types导航到编辑器 -> 文件类型
  3. Find Python and add __init__.py to the list of python files找到 Python 并将__init__.py添加到 Python 文件列表中

or或者

  1. Find Text and delete __init__.py from the list of text files查找 Text 并从文本文件列表中删除__init__.py

The project I cloned had a directory called modules and was successfully using files from there in the code with import this as that , but Pycharm was unable to jump to those code fragments because it did not recognise the imports.我克隆的项目有一个名为modules的目录,并成功地在代码中使用import this as that中的文件,但 Pycharm 无法跳转到这些代码片段,因为它无法识别导入。

Marking the module folder in the following settings section as source solved the issue.将以下设置部分中的模块文件夹标记source解决了该问题。

Pycharm 首选项

一般来说,这是一个缺少包的问题,​​只需将插入符号放在未解析的引用处,然后按Alt+Enter显示选项,然后您应该知道如何解决它。

Although all the answers are really helpful, there's one tiny piece of information that should be explained explicitly:尽管所有答案都非常有帮助,但仍有一小部分信息需要明确解释:

  • Essentially, a project with multiple hierarchical directories work as a package with some attributes.本质上,具有多个分层目录的项目作为具有某些属性的包工作。
  • To import custom local created Classes, we need to navigate to the directory containing .py file and create an __init__.py (empty) file there.要导入自定义本地创建的类,我们需要导航到包含.py文件的目录并在那里创建一个__init__.py (空)文件。

Why this helps is because this file is required to make Python treat the directory as containing packages.为什么这会有所帮助,因为需要此文件才能使 Python 将目录视为包含包。 Cheers!干杯!

Install via PyCharm (works with Community Edition).通过 PyCharm 安装(与社区版一起使用)。 Open up Settings > Project > Project Interpreter then click the green + icon in the screenshot below.打开Settings > Project > Project Interpreter ,然后单击下面屏幕截图中的绿色 + 图标。 In the 2nd dialogue that opens, enter the package name and click the 'Install Package' button.在打开的第二个对话框中,输入包名称并单击“安装包”按钮。

在此处输入图像描述

After following the accepted answer, doing the following solved it for me:遵循接受的答案后,执行以下操作为我解决了这个问题:

FileSettingsProject <your directory/project>Project Dependencies FileSettingsProject <your directory/project>Project Dependencies

Chose the directory/project where your file that has unresolved imports resides and check the box to tell Pycharm that that project depends on your other project.选择具有未解析导入的文件所在的目录/项目,并选中该框以告诉 Pycharm 该项目依赖于您的其他项目。

My folder hierarcy is slightly different from the one in the question.我的文件夹层次结构与问题中的文件夹层次结构略有不同。 Mine is like this我的是这样的

├── MyDirectory  
│     └── simulate.py  
├── src  
│     ├── networkAlgorithm.py  
│     ├── ...

Telling Pycharm that src depends on MyDirectory solved the issue for me!告诉 Pycharm src 依赖于MyDirectory为我解决了这个问题!

这对我有用: Top Menu -> File -> Invalidate Caches/Restart

  1. --> Right-click on the directory where your files are located in PyCharm --> 右键单击​​ PyCharm 中文件所在的目录
  2. Go to the --> Mark Directory as转到 --> 将目录标记为
  3. Select the --> Source Root选择 --> 源根

your problem will be solved你的问题将得到解决

Many a times what happens is that the plugin is not installed.很多时候发生的是插件没有安装。 eg例如

If you are developing a django project and you do not have django plugin installed in pyCharm, it says error 'unresolved reference'.如果您正在开发一个 django 项目并且您没有在 pyCharm 中安装 django 插件,它会显示错误“未解析的引用”。 Refer: https://www.jetbrains.com/pycharm/help/resolving-references.html参考: https ://www.jetbrains.com/pycharm/help/resolving-references.html

我也使用了像上面 Dan 这样的虚拟环境,但是我能够在现有环境中添加解释器,因此不需要继承全局站点包,因此不需要撤销虚拟环境试图实现的功能。

Please check if you are using the right interpreter that you are supposed to.请检查您是否使用了正确的口译员。 I was getting error "unresolved reference 'django' " to solve this I changed Project Interpreter (Changed Python 3 to Python 2.7) from project settings: Select Project, go to File -> Settings -> Project: -> Project Interpreter -> Brows and Select correct version or Interpreter (eg /usr/bin/python2.7).我收到错误“未解析的引用'django'”来解决这个问题我从项目设置中更改了项目解释器(将Python 3更改为Python 2.7):选择项目,转到文件->设置->项目:->项目解释器->浏览并选择正确的版本或解释器(例如 /usr/bin/python2.7)。

In my case the problem was I was using Virtual environment which didn't have access to global site-packages.就我而言,问题是我使用的是无法访问全局站点包的Virtual environment Thus, the interpreter was not aware of the newly installed packages.因此,解释器不知道新安装的软件包。

To resolve the issue, just edit or recreate your virtual interpreter and tick the Inherit global site-packages option.要解决此问题,只需编辑或重新创建您的虚拟解释器并勾选Inherit global site-packages选项。

在此处输入图像描述

在 PyCharm 2019.3.1 中完成右键单击​​您的 src 文件夹->“将目录标记为”-> 单击“已排除” ,您的 src 文件夹应该是蓝色的。

For my case :对于我的情况:

Directory0
    ├── Directory1
    │     └── file1.py  
    ├── Directory2
    │     ├── file2.py  

Into file1, I have :进入file1,我有:

from Directory2 import file2

which trows an "unresolved reference Directory2".这会引发“未解析的参考 Directory2”。

I resolved it by:我通过以下方式解决了它:

  • marking the parent directory Directory0 as "Source Root" like said above如上所述将父目录 Directory0 标记为“源根”

AND

  • putting my cursor on another line on the file where I had the error so that it takes my modification into account将光标放在出现错误的文件的另一行上,以便将我的修改考虑在内

It is silly but if I don't do the second action, the error still appears and can make you think that you didn't resolve the issue by marking the parent directory as Source Root.这很愚蠢,但如果我不执行第二个操作,错误仍然会出现,并且可以让您认为您没有通过将父目录标记为 Source Root 来解决问题。

For me, adding virtualenv ( venv )'s site-packages path to the paths of the interpreter works.对我来说,将 virtualenv ( venv ) 的站点包路径添加到解释器的路径中是可行的。 Finally!最后!

在此处输入图像描述

I tried everything here twice and even more.我在这里尝试了两次甚至更多。 I finally solved it doing something I hadn't seen anywhere online.我终于解决了它,做了一些我在网上从未见过的事情。 If you go to Settings>Editor>File Types there is an 'Ignore Files and folders ' line at the bottom.如果您转到Settings>Editor>File Types ,则底部有一个'Ignore Files and folders ”行。 In my case, I was ignoring 'venv' , which is what I always name my virtual environments.就我而言,我忽略了'venv' ,这是我一直为我的虚拟环境命名的。 So I removed venv;所以我删除venv; from the list of directories to ignore and VOILA!!从目录列表中忽略和瞧! I was FINALLY able to fix this problem.我终于能够解决这个问题。 Literally all of my import problems were fixed for the project.从字面上看,我的所有导入问题都已针对该项目进行了修复。

BTW, I had installed each and every package using PyCharm, and not through a terminal.顺便说一句,我已经使用 PyCharm 安装了每个包,而不是通过终端。 (Meaning, by going to Settings>Interpreter... ). (意思是,通过转到Settings>Interpreter... )。 I had invalidated cache, changed 'Source Root', restarted PyCharm, refreshed my interpreters paths, changed interpreters, deleted my venv... I tried everything.我已经使缓存无效,更改了“源根”,重新启动 PyCharm,刷新了我的解释器路径,更改了解释器,删除了我的 venv ......我尝试了一切。 This finally worked.这终于奏效了。 Obviously there are multiple problems going on here with different people, so this may not work for you, but it's definitely worth a shot if nothing else has worked, and easy to reverse if it doesn't.显然,不同的人在这里会遇到多个问题,所以这可能对你不起作用,但如果没有其他方法起作用,它绝对值得一试,如果不起作用,也很容易扭转。

I had the same problem and also try so many suggestions but none of them worked, until I find this post ( https://stackoverflow.com/a/62632870/16863617 ).我遇到了同样的问题,也尝试了很多建议,但都没有奏效,直到我找到这篇文章( https://stackoverflow.com/a/62632870/16863617 )。 Regardless his solution didn't work for me, it helped me to came up with the idea to add _ init.py _ into the --> Settings |不管他的解决方案对我不起作用,它帮助我想出了将_init.py _ 添加到 --> Settings | Editor |编辑 | File Types |文件类型 | Python |蟒蛇 | Registered patterns注册模式

ScreenShot截屏

And the unresolved reference error is now solved.现在解决了未解决的参考错误。

请注意,如果您遇到 python 解释器未安装软件包的问题,​​只需将文件夹PycharmProjects C:\Users'username'\PycharmProjects 的权限更改为每个

This problem also appears if you use a dash within the Python filename, which therefore is strongly discouraged.如果您在 Python 文件名中使用破折号也会出现此问题,因此强烈建议不要这样做。

I encountered an import problem when installing aiogram.我在安装 aiogram 时遇到导入问题。 At the same time, the bot worked, but pyCharm highlighted the import in red and did not give hints.同时,该机器人工作了,但 pyCharm 以红色突出显示了导入并且没有给出提示。 I've tried all of the above many times.As a result, the following helped me: I found the aiogram folder at the following path c\Users...\AppData\Roaming\Python\Python310\site-packages and copied it to the folder C:\Program Files\Python310\Lib\site-packages After that, I reset pyCharm and that's it!我已经多次尝试以上所有方法。结果,以下帮助了我:我在以下路径c\Users...\AppData\Roaming\Python\Python310\site-packages找到了aiogram文件夹并将其复制到文件夹C:\Program Files\Python310\Lib\site-packages之后,我重置 pyCharm 就是这样!

In my case, with Pycharm 2019.3, the problem was that I forgot to add the extension '.py' to the file I wanted to import.就我而言,使用 Pycharm 2019.3,问题是我忘记将扩展名“.py”添加到我想要导入的文件中。 Once added, the error went away without needing to invalides caches or any other step.添加后,错误消失,无需使缓存无效或任何其他步骤。

Pycharm uses venv. Pycharm 使用 venv。 In the venv's console you should install the packages explicitly or go in settings -> project interpreter -> add interpreter -> inherit global site-packages .在 venv 的控制台中,您应该显式安装包或进入settings -> project interpreter -> add interpreter -> inherit global site-packages

The easiest way to fix it is by doing the following in your pyCharm software:修复它的最简单方法是在 pyCharm 软件中执行以下操作:

Click on: File > Settings > (Project: your project name) > Project Interpreter >点击:文件>设置>(项目:你的项目名称)>项目解释器>

then click on the "+" icon on the right side to search for the package you want and install it.然后单击右侧的“+”图标搜索您想要的软件包并安装它。

Enjoy coding !!!享受编码!

在较新版本的 pycharm 中,您只需右键单击要从中导入文件的目录或 python 包,然后单击“将目录标记为”->“源根”即可

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM