【问题标题】:Is it possible to import all modules within a package from a a different directory in python 3.8?是否可以从 python 3.8 中的不同目录导入包中的所有模块?
【发布时间】:2020-12-06 21:43:12
【问题描述】:

我正在使用 Python 3.8。我有一个这样的目录结构:

├── package
│   ├── __init__.py
│   └── test2.py
└── test.py

test2的内容:

def x():
   print(999)

__init__.py 的内容:

from test2 import *

test.py 的内容:

import package
package.x()

运行 test.py 出现以下错误:

  from test2 import *
ModuleNotFoundError: No module named 'test2'

我希望 test.py 按预期工作。请帮忙。

【问题讨论】:

  • 我觉得应该是from .test2
  • 导入 test 2 也许试试这个:import package.test2
  • @hjpotter92 谢谢。它解决了问题

标签: python python-3.x python-3.6 python-3.7


【解决方案1】:

正如@hjpotter92 所说,问题出在__init__.py 文件中,因为输入应该是:

from .test2 import *

然后要在test.py 中使用test2.py 中的函数,您只需要这样的东西:

import package
package.x()

Here您可以找到有关此主题的更多信息和一些建议。

编辑:

您必须使用from .test2 import * 而不是from test2 import * 导入的主要原因是因为test2 在Python 称为package 的内部(您调用了同名的目录)并且它应该在外部使用同一个包(在test.py中),否则你不需要使用.来导入它。

例如,如果您有这样的结构:

├── package
│   ├── __init__.py
│   └── test2.py
|   └── test3.py
└── test.py

在test3.py 你可以这样做:from test2 import x 因为在同一个package(命名包)中

. 代表模块所在的包,例如,如果你想在不使用__init__.py 的情况下导入test.py,你应该这样做:from package.test2 import *

希望对你有帮助:)

【讨论】:

  • 你能解释一下为什么'from test2 import *'不起作用。它在 IDLE 中工作
猜你喜欢
  • 2012-05-19
  • 2019-04-05
  • 1970-01-01
  • 2013-05-27
  • 1970-01-01
  • 2012-02-15
相关资源
最近更新 更多