<分区>
我有一个 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 3和 Relative import in Python 3 not working .
我怀疑它可能与 virtualenv 有关,但 a) 我不明白为什么工作目录不是 PYTHONPATH 的一部分,b) 我不太确定如何在 virtualenv 中更改它 - Intellij 为我设置了它。