【发布时间】:2019-05-16 08:26:01
【问题描述】:
最近我发现在使用“import M”和“from .import M”时会出现奇怪的错误。我正在使用 python3.6。
例如,文档树如下。
test/
├── pacA
│ ├── a1.py
│ ├── a2.py
│ └── utils.py
├── test_a1.py
└── test_a2.py
在 utils.py 中是 func 打印机:
def printer(info):
print(info)
在 a1.py 中是:
from .utils import printer
def pa():
printer('printer called in a1.pa()\n')
if __name__ == '__main__':
printer('pinter called in a1.__main__\n')
在a2.py中是:
from utils import printer
def pa():
printer('printer called in a2.pa()\n')
if __name__ == '__main__':
printer('pinter called in a2.__main__\n')
我们可以看到a1.py和a2.py都想在utils.py中导入打印机。他们使用不同的导入方法。这是唯一的区别。
当我从目录 pacA/ 运行 a1.py 时,我得到以下错误:
from .utils import printer
ModuleNotFoundError: No module named '__main__.utils'; '__main__' is not a package
但是运行 a2.py 会得到正确的答案。
但是,如果我使用另一个 .py 导入 a1 和 a2,事情就会好转。在test_a1.py中,代码如下:
from pacA import a1
if __name__ == '__main__':
a1.pa()
在test_a2.py中,代码如下:
from pacA import a2
if __name__ == '__main__':
a2.pa()
当我运行 test_a1.py 时,无论是否来自 test/,我都会得到正确的答案。但是,当我运行 test_a2.py 时,出现如下错误:
from pacA import a2
File "/home/gph/Desktop/test/pacA/a2.py", line 1, in <module>
from utils import printer
ModuleNotFoundError: No module named 'utils'
我应该如何在 a1 中导入 utils.py 以使这两种情况都正确?
【问题讨论】:
标签: python python-3.x import