python中"import module"和"from . import module"之间的区别?



最近我发现使用"导入m"one_answers"来自。导入m"时存在奇怪的错误。我正在使用python3.6。
例如,doucment树是贝洛斯。

test/
├── pacA
│   ├── a1.py
│   ├── a2.py
│   └── utils.py
├── test_a1.py
└── test_a2.py

in 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_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以使这两种情况对吗?

尝试这个

pip install utils

Python希望您安装Utils软件包外部

希望这有帮助

我想我找到了这一点的原因。

对于第一个错误,我不直接运行A1.PY。当您在A1.PY中使用相对导入的from .utils import printer时,则不应直接运行A1.PY。如果是这样,您将获得错误'__main__' is not a package"。要了解这一点,您需要知道if __name__==__main__的工作原理。

在A2.PY中使用from utils import printer时,Python将搜索经典路径,包括在SYS.Path中。但是,如果您运行test_a2.py,则不包括paca,因此我们找不到它。如果要运行test.a2.py,则在导入utils之前应包含此 sys.path.append('path to pacA')

最新更新