【发布时间】:2015-07-28 19:34:44
【问题描述】:
我有一个 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 为我设置了它。
【问题讨论】:
标签: python python-3.x intellij-idea import