是否可以从python 3.8中的其他目录导入包中的所有模块?

问题描述

我正在使用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能够按预期工作。请帮忙。

解决方法

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

from .test2 import *

然后使用test2.pytest.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(命名包)中

.代表模块所在的包,例如,如果您想在不使用test.py的情况下导入__init__.py,则应执行以下操作:from package.test2 import * >

希望这可以为您提供帮助:)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...