Pycharm“没有名为REPORT.py的模块”,不管它是如何存在和工作的。但是后来呢

2024-05-23 21:11:46 发布

您现在位置:Python中文网/ 问答频道 /正文

Pycharm说REPORT.py文件不存在。然而,代码工作得很完美

以下是问题的图像:

enter image description here

这不是最奇怪的部分。我知道有时在一个包中工作时,必须引用包名:import package_name.filename,所以当我尝试时,它似乎已经修复了错误的报告

enter image description here

但是

Traceback (most recent call last):
  File "C:/Users/REDACTED/PycharmProjects/REDACTED/MAIN/MAIN.py", line 2, in <module>
    import MAIN.REPORTS as PDD
  File "C:\Users\REDACTED\PycharmProjects\REDACTED\MAIN\MAIN.py", line 2, in <module>
    import MAIN.REPORTS as PDD
ModuleNotFoundError: No module named 'MAIN.REPORTS'; 'MAIN' is not a package

这就像是Pycharm检查我文件的错误

为了完整性,我也尝试从导入

enter image description here

Pycharm也没有将其标记为无效,但在运行代码时,我遇到了一个新的有趣错误:

Traceback (most recent call last):
  File "C:/Users/REDACTED/PycharmProjects/REDACTED/MAIN/MAIN.py", line 2, in <module>
    from MAIN import REPORTS as PDD
  File "C:\Users\REDACTED\PycharmProjects\REDACTED\MAIN\MAIN.py", line 2, in <module>
    from MAIN import REPORTS as PDD
ImportError: cannot import name 'REPORTS'

根据评论中的要求,这里是我的文件夹结构:

enter image description here

根据评论中的建议,我确实尝试导入*但我仍然从Pycharm获得相同的报告问题

enter image description here

更新:

我相信我在尝试从我的包导入时发现了问题存在的原因

由于我的包名是MAIN,而我的主py文件是MAIN.py,我相信我的代码试图从py文件而不是包导入

将我的包重命名为MAIN_PACK并执行import MAIN_PACK.REPORT as PDD之后,代码工作正常,Pycharm没有任何报告说它无效

这至少修复了Pycharm报告

However that still does not explain why Pycharm reports that import REPORTS is not a module but still the code would work.Does anyone know why this is occurring?


Tags: 文件代码pyimportmainas报告users
1条回答
网友
1楼 · 发布于 2024-05-23 21:11:46

将主文件夹设置为源根目录。您可以通过右键单击主文件夹并导航到列表底部来完成此操作。将目录标记为源根目录。进入console下的Pycharm设置并选中将源根添加到python路径。

Pycharm使用源根解析导入。更多信息可以在这里找到

https://www.jetbrains.com/help/pycharm/content-root.html

链接中的相关文本:

Source roots (or source folders; shown as the Source root icon ).

  • These roots contain the actual source files and resources. PyCharm uses the source roots as the starting point for resolving imports. The files under the source roots are interpreted according to their type. PyCharm can parse, inspect, index, and compile the contents of these roots.

相关问题 更多 >