python包的相对导入与绝对导入使用

一、错误使用,造成的错误描述如下:

ModuleNotFoundError: No module named "__main__.operation"; "__main__" is not a package

ModuleNotFoundError: No module named "operation"

ValueError: attempted relative import beyond top-level package
 

二、实例目录结构:

cur_path
│
├─packages
│   ├─__init__.py
│   ├─ui.py
│   │
│   ├─operation
│   │    ├─__init__.py
│   │    ├─mixed_operation.py
│   │    └─simple_operation.py
│   │
│   └─util
│       ├─__init__.py
│       ├─add.py
│       ├─div.py
│       ├─mul.py
│       └─sub.py
└─main.py

三、示例:

1、main.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from packages.ui import main
if __name__ == "__main__":
    main()

2、packages/ui.py

from .operation.mixed_operation import mix
def main():
    mix()
if __name__ == "__main__":
    main()

3、packages/operation/mixed_operation.py

from .simple_operation import *
def mix():
    num = one_add_two() + three_mul_four() + five_sub_six() + seven_sub_eight()
    print("1 + 2 + 3 * 4 + 5 - 6 + 7 / 8 = ", num)

4、packages/operation/simple_operation.py

from ..util.add import add
from ..util.sub import sub
from ..util.mul import mul
from ..util.div import div
def one_add_two():
    return add(1, 2)
    
def three_mul_four():
    return mul(3, 4)
    
def five_sub_six():
    return sub(5, 6)
    
def seven_sub_eight():
    return div(7, 8)
    
__all__ = ["one_add_two", "three_mul_four", "five_sub_six", "seven_sub_eight"]

5、packages/util/add.py

def add(a, b):
    return a + b

6、packages/util/div.py

def div(a, b):
    return a / b

7、packages/util/mul.py

def mul(a, b):
    return a * b

8、packages/util/sub.py

def sub(a, b):
    return a - b

四、运行方式:

1、正确运行方式:

python -m packages.ui
python main.py

2、错误运行方式以及错误描述

# 直接运行的脚本中不能含有相对导入
python packages/ui.py
Traceback (most recent call last):
  File "packages/ui.py", line 6, in <module>
    from .operation.mixed_operation import mix
ModuleNotFoundError: No module named "__main__.operation"; "__main__" is not a package
################################

# 模块方式,引入当前需要添加.号
# ui.py中的from后没有.
python -m packages.ui
packagesui.py", line 3, in <module>
    from operation.mixed_operation import mix
ModuleNotFoundError: No module named "operation"