Python: 关于 Package 和 Module 快速入门
建议点击 查看原文 查看最新内容。
原文链接:
https://typonotes.com/posts/2024/11/29/python-package-module-quick-start/
什么是 包 (Package)
如果一个目录中有 __init__.py , 那这个目录就是 包 Package
什么是 模块 (Module)
xxx.py 文件就是模块
怎么引用自定义包
把 包路径 使用 sys.path.append(xxx) 添加后, 就可以使用
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
 | # import {Package}
from x.Package import Module
print(f"Module.Attribute")
from x.Package.Module import Attribute
print(f"{Attribute}")
# 别名
from x.Package.Module import Attribute as attr
print(f"{attr}")
 | 
不能使用 连续的 . 结构
| 1
2
 | import x.Package
print(f"{Package.Module.Attribute}")
 | 

Package and Module Practice
| 1
2
3
4
5
6
7
8
 | app/
├── __init__.py         # Optional for Python 3.3+, but helps clarify it's a package
├── config/
│   ├── __init__.py     # Makes 'config' a subpackage
│   └── config.py
├── ecs/
│   ├── __init__.py     # Makes 'ecs' a subpackage
│   └── ecs.py
 | 
1. 使用文件方式执行 - 绝对路径
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
 | # app/ecs/ecs.py
import sys
import os
# Add the parent directory to sys.path to make 'config' importable
## 添加上了 app 到 sys.path 中
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
## 使用绝对路径引用
from config.config import ACCESS_KEY
def main():
    print(f"The AWS Access Key is: {ACCESS_KEY}")
if __name__ == "__main__":
    main()
 | 
才能 在本地路径中 使用文件方式执行, 才能使用 兄弟目录 的模块。
也可以回到 根目录 使用模块方式启动
| 1
2
 | cd app
python -m ecs.ecs
 | 
2. 使用模块方式执行 - 相对路径
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
 | # app/ecs/ecs.py
# Relative import of ACCESS_KEY from config module
from ..config.config import ACCESS_KEY
def main():
    print(f"The AWS Access Key is: {ACCESS_KEY}")
if __name__ == "__main__":
    main()
 | 
使用 相对路径 引用模块, 只能使用 模块方式 启动。 且启动位置只能是 根目录
| 1
2
 | cd app
python -m ecs.ecs
 | 
The -m flag runs the module in a package-aware manner, which allows Python to resolve relative imports properly. If you run ecs.py directly as a script (python ecs.py), Python won’t recognize it as part of the app package, and the relative import will fail.