python - Intellij idea 无法识别 python 3 中本地类的导入

标签 python python-3.x intellij-idea import

<分区>

我有一个 python3 脚本 script.py,我想在其中实例化一个在 clazz.py 中定义的类 Foobar。但是,当我尝试导入时,我得到:

$ python3 script.py
...
SystemError: Parent module '' not loaded, cannot perform relative import

这是我的文件结构:

python_import/
├── __init__.py
├── clazz.py
└── script.py

clazz.py:

class Foobar():
    def __init__(self):
        print("initialized a foobar")

脚本.py:

from .clazz import Foobar
foobar = Foobar()

如果我在 import 中删除 .,它运行良好;但是,如果我这样做,我的 IDE (Intellij IDEA) 会在导入中用红色下划线,并且不会自动完成任何内容。我相信包含 . 在 python3 中是正确的,而且 Intellij 似乎喜欢它,那么为什么我的程序不能运行除非我删除它?

我已阅读 http://www.diveintopython3.net/porting-code-to-python-3-with-2to3.html#import , http://python.readthedocs.org/en/latest/reference/import.html , How to import the class within the same directory or sub directory? , Relative imports in Python 3Relative import in Python 3 not working .

我怀疑它可能与 virtualenv 有关,但 a) 我不明白为什么工作目录不是 PYTHONPATH 的一部分,b) 我不太确定如何在 virtualenv 中更改它 - Intellij 为我设置了它。

最佳答案

你的 IDE 喜欢 . 的原因是它知道你的脚本在包 python_import/ 中,但是当你通过命令行运行它时,解释器对包一无所知,所以相对导入将不起作用。

消除“unresolved reference”的红线错误,见Unresolved reference issue in PyCharm , 一步步完善。

关于python - Intellij idea 无法识别 python 3 中本地类的导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30283858/

相关文章:

python - 理解为什么来自不同代码的这些操作码是相同的

python - 这个错误: "TypeError: Parameters to generic types must be types"?是什么意思

json - 从调试器获取 IntelliJ Idea 中的 JSON 对象

python扭曲的中间人实现

python - Matplotlib 将图像文件旋转 X 度

python - 在 windbg 中调试 python 转储文件

python - 给定一个 Python 列表列表,找到所有可能的保持每个子列表顺序的平面列表?

python - 属性错误: 'NoneType' object has no attribute 'lower

maven - Storm-starter与intellij idea,maven项目找不到类

java.lang.ClassNotFoundException : text. 默认源