Python函数-模块
一、模块和包
1、概念
- 模块(module) 就是一个
.py文件; - 包(package) 是含
__init__.py的目录,可嵌套子包; - import 的本质是按 搜索路径 找到模块/包,把它变成 对象 放到当前命名空间。
2、文件结构示例
myproj/ # 项目根├── mypkg/ # 包│ ├── __init__.py # 包初始化(可为空)│ ├── mod_a.py # 模块│ └── subpkg/ # 子包│ ├── __init__.py│ └── mod_b.py└── main.py # 主脚本3、搜索顺序(sys.path)
- 当前脚本所在目录
- PYTHONPATH 环境变量
- 标准库目录
- site-packages(第三方包)
import sysprint(sys.path)拓展:添加指定路径
3.1、四种方法速查表
| 方法 | 典型语法 | 作用域 | 生命周期 | 适用场景 |
|---|---|---|---|---|
运行时修改 sys.path | import sys; sys.path.insert(0, '/abs/path') | 仅当前进程 | 进程结束即失效 | 脚本/REPL 临时调试 |
设置环境变量 PYTHONPATH | export PYTHONPATH=/abs/path:$PYTHONPATH | 当前 shell 及其子进程 | 会话级 | 开发机本地、CI 脚本 |
| .pth 文件 | 在任意 site-packages 目录新建 my.pth,内容一行:/abs/path | 全局解释器 | 永久生效 | 所有项目共享工具目录 |
包内相对导入 + pip install -e | pip install -e .(项目根含 setup.cfg/pyproject.toml) | 虚拟环境 | 直到卸载 | 正式项目/库开发 |
3.2、逐条说明与示例
3.2.1、运行时修改 sys.path(最灵活)
项目结构:
myproj/ # 项目根├── commons/ # 包│ ├── __init__.py # 包初始化(可为空)│ ├── mod_a.py # 模块│ └── subpkg/ # 子包│ ├── __init__.py│ └── mod_b.py└── bin/ ├── __init__.py └── run.py # 项目执行文件import osimport sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))- 优点:无需重启解释器,可动态计算路径。
- 缺点:只对当前进程有效;写在脚本里别人看不到。
3.2.2、环境变量 PYTHONPATH(开发常用)
- Linux/macOS:
export PYTHONPATH=$HOME/projects/toolkit:$PYTHONPATHpython script.py- Windows PowerShell:
$Env:PYTHONPATH = "C:\projects\toolkit;$Env:PYTHONPATH"- 优点:一次设置,当前终端及其子进程均可
import toolkit。 - 缺点:换终端/IDE 需重新设置;发布给他人不方便。
3.2.3、.pth 文件(“一次配置,永久生效”)
-
找到当前解释器的 site-packages 目录:
import site, pathlibprint(pathlib.Path(site.getsitepackages()[0]) / "my_extra.pth") -
新建
my_extra.pth,内容只需一行:/absolute/path/to/your/dir -
保存后任何新启动的该解释器都会自动把目录加入
sys.path。
- 优点:跨项目、跨终端生效;无需改动代码。
- 缺点:需要写文件权限;路径为绝对路径。
3.2.4、包内相对导入 + 开发安装(推荐用于正式项目)
项目结构:
myproj/├── pyproject.toml└── mypkg/ ├── __init__.py └── utils.pypyproject.toml 最少内容:
[project]name = "mypkg"version = "0.1.0"安装到当前虚拟环境:
cd myprojpython -m pip install -e .- 效果:
mypkg被“链接”到 site-packages,任何路径下都能import mypkg。 - 优点:符合打包规范,可发布。
- 缺点:需要简单打包描述,但现代工具(Poetry、PDM、Hatch)已极大简化。
4、导入包的方法
| 语法 | 效果 |
|---|---|
import pkg | 将包 pkg 整体加载,并用同名变量 pkg 引用 |
import pkg1, pkg2 | 一次性加载多个包,分别用同名变量 pkg1、pkg2 引用 |
import pkg as alias | 将包 pkg 整体加载,并用自定义别名 alias 引用 |
import pkg1 as alias1, pkg2 as alias2 | 同时加载多个包,并分别用别名 alias1、alias2 引用 |
import superpkg.subpkg | 将子包 superpkg.subpkg 整体加载,并用同名变量 superpkg.subpkg 引用 |
from superpkg import subpkg | 将子包 subpkg 直接导入当前命名空间,可直接使用 subpkg 调用 |
5、导入模块的方法
| 语法 | 效果 |
|---|---|
import pkg.mod | 把包 pkg 中的模块 mod 整体载入,使用时必须写全限定名 pkg.mod.xxx。 |
import pkg.mod as alias | 同上,但把模块绑定到自定义别名 alias,后续用 alias.xxx 调用,简化或避免命名冲突。 |
from pkg import mod | 只把模块对象 mod 从包 pkg 中“提取”到当前命名空间,使用时直接写 mod.xxx,无需再写包前缀。 |
from pkg.mod import func | 把模块 pkg.mod 中的具体对象(如函数、类、变量)func 直接放入当前命名空间,使用时直接写 func() 或 func。 |
6、绝对 vs 相对导入
| 类型 | 写法 | 说明 |
|---|---|---|
| 绝对 | import mypkg.mod_a | 从 搜索路径根 开始找 |
| 相对 | from . import mod_a | . 当前包,.. 父包(只能在包内部用) |
from .subpkg import mod_b # 相对导入import mypkg.subpkg.mod_b # 绝对导入7、常见坑 & 修复
| 坑 | 现象 | 修复 |
|---|---|---|
| 循环导入 | ImportError | 延迟导入(函数内 import)或重构 |
| 相对导入脚本 | ModuleNotFoundError | 用 -m 运行包,或改为绝对导入 |
| 同名文件挡住标准库 | 标准库被覆盖 | 改名或调整 sys.path |
| 包内直接运行 | __main__ 路径错 | 使用 python -m mypkg.mod |
8、执行入口(主函数)
8.1、基本语法
def main(): # 主要的程序逻辑 print("这是主函数")
if __name__ == "__main__": main()8.2、__name__ 变量的作用
- 当 Python 文件被直接运行时,
__name__的值为 “__main__” - 当 Python 文件被导入为模块时,
__name__的值为模块名(文件名)
def helper_function(): """一个辅助函数""" print("辅助函数被调用")
def main(): """主函数,程序的入口点""" print("程序开始执行") helper_function() print("程序执行结束")
# 这是标准的执行入口检查if __name__ == "__main__": main()二、第三方模块
1、什么是“第三方模块”
- 标准库:Python 官方随解释器一起发布的模块,如
os、json、datetime等。 - 第三方模块(third-party packages):由社区或个人开发、托管在 PyPI(Python Package Index)上的模块/包,需要用户额外安装才能使用,如
requests、numpy、pandas、flask、django等。 - 本质:放在
site-packages目录下的目录或.whl/.tar.gz安装包,包含模块代码和元数据(METADATA、setup.py、pyproject.toml等)。
2、常用安装方式
2.1、pip(99 % 场景)
-
概念:官方包管理器,自动下载 → 选 wheel → 回退源码 → 编译(如需要)。
-
常用命令:
# 安装python -m pip install 包名# 指定版本python -m pip install "包名>=1.2,<2.0"# 升级python -m pip install -U 包名# 卸载python -m pip uninstall 包名# 根据锁文件批量安装python -m pip install -r requirements.txt# 离线:先下载再装python -m pip download -d wheelhouse -r requirements.txtpython -m pip install --no-index --find-links wheelhouse -r requirements.txt
2.2、wheel(二进制包,后缀 .whl)
-
概念:已编译好的“快递包裹”,复制即可用,跨平台需 tag 匹配。
-
常用命令:
# 直接装本地 wheelpython -m pip install somepkg-1.0-cp312-cp312-win_amd64.whl# 自己打包 wheelpython -m build # 生成 dist/*.whltwine upload dist/* # 推到 PyPI
2.3、源码(sdist,.tar.gz / .zip)
-
概念:最原始压缩包,任何平台都能编;缺 wheel 或需要改代码时用。
-
常用命令:
# 1、解压tar -xf package-1.0.tar.gzcd package-1.0# 2、构建(可选,setup.py 会自动 build)python setup.py build# 3、安装python setup.py install # 全局python setup.py install --user # 仅当前用户
2.4、Conda(科学计算全家桶)
-
概念:带 C/Fortran/CUDA 依赖的大型二进制仓库,与 pip 互不干扰。
-
常用命令:
conda install numpyconda install pytorch torchvision -c pytorch# 导出/恢复环境conda env export > env.ymlconda env create -f env.yml
2.5、系统包管理器(apt/yum/brew)
-
概念:操作系统层面的 Python 包,版本通常滞后,但和系统库耦合。
-
常用命令:
sudo apt install python3-numpysudo yum install python3-lxmlbrew install python-tkinter
2.6、私有源 / Git / 本地路径
# Git 直接装python -m pip install git+https://github.com/user/proj.git@main# 私有 PyPIpython -m pip install --extra-index-url https://pypi.company.com/simple 私有包# 本地目录python -m pip install ./myproject3、注意事项
-
使用虚拟环境(venv、conda env、poetry、pipenv)避免包冲突。
-
国内用户建议配置镜像:
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple# 也还有其他的源可供选择(豆瓣应用广泛)豆瓣:https://pypi.douban.com/simple/阿里云:http://mirrors.aliyun.com/pypi/simple/中国科技大学:https://pypi.mirrors.ustc.edu.cn/simple/清华大学:https://pypi.tuna.tsinghua.edu.cn/simple/中国科学技术大学:http://pypi.mirrors.ustc.edu.cn/simple/ -
部分带 C 扩展的包(如
numpy,lxml)在 Windows 上推荐直接用 pip 下载预编译 wheel;若失败,可改用 conda。 -
如果同时装了 Python2/3,使用
python3 -m pip或py -3 -m pip明确版本。
三、内置模块
_thread | abc | aifc | argparse | array |
ast | asynchat | asyncio | asyncore | atexit |
audioop | base64 | bdb | binascii | binhex |
bisect | builtins | bz2 | calendar | cgi |
cgitb | chunk | cmath | cmd | code |
codecs | codeop | collections | colorsys | compileall |
concurrent | configparser | contextlib | contextvars | copy |
copyreg | cProfile | crypt | csv | ctypes |
curses | dataclasses | datetime | dbm | decimal |
difflib | dis | distutils | doctest | email |
encodings | ensurepip | enum | errno | faulthandler |
fcntl | filecmp | fileinput | fnmatch | fractions |
ftplib | functools | gc | getopt | getpass |
gettext | glob | grp | gzip | hashlib |
heapq | hmac | html | http | imaplib |
imghdr | imp | importlib | inspect | io |
ipaddress | itertools | json | keyword | lib2to3 |
linecache | locale | logging | lzma | mailbox |
mailcap | marshal | math | mimetypes | mmap |
modulefinder | msilib | msvcrt | multiprocessing | netrc |
nis | nntplib | ntpath | numbers | operator |
optparse | os | ossaudiodev | parser | pathlib |
pdb | pickle | pickletools | pipes | pkgutil |
platform | plistlib | poplib | posix | posixpath |
pprint | profile | pstats | pty | pwd |
py_compile | pyclbr | pydoc | queue | quopri |
random | re | readline | reprlib | resource |
rlcompleter | runpy | sched | secrets | select |
selectors | shelve | shlex | shutil | signal |
site | smtpd | smtplib | sndhdr | socket |
socketserver | spwd | sqlite3 | ssl | stat |
statistics | string | stringprep | struct | subprocess |
sunau | symbol | symtable | sys | sysconfig |
syslog | tabnanny | tarfile | telnetlib | tempfile |
termios | textwrap | this | threading | time |
timeit | tkinter | token | tokenize | trace |
traceback | tracemalloc | tty | turtle | turtledemo |
types | typing | unicodedata | unittest | urllib |
uu | uuid | venv | warnings | wave |
weakref | webbrowser | winreg | winsound | wsgiref |
xdrlib | xml | zipapp | zipfile | zipimport |
zlib |
1、语言基础 & 运行时
1.1、sys
作用:与 Python 解释器交互。
import syssys.argv # 命令行参数列表sys.exit(1) # 立即终止进程sys.path # 模块搜索路径sys.stderr.write('error\n')1.2、builtins(隐式加载)
作用:存放所有内建函数/异常;可覆盖或增强。
__builtins__.len([1,2,3]) # 直接访问1.3、gc
作用:手动控制垃圾回收。
import gcgc.collect() # 立即回收gc.disable() # 关闭自动回收2、数据类型增强
2.1、collections
作用:高性能容器数据类型。
from collections import Counter, defaultdict, dequeCounter('abracadabra') # 计数d = defaultdict(list); d['a'] # 默认空列表dq = deque(maxlen=5) # 双端队列2.2、itertools
作用:迭代器“工具箱”,惰性求值,节省内存。
from itertools import chain, islice, groupbylist(chain([1,2], [3,4])) # 扁平化for k, g in groupby('AAABBB'): # 分组 print(k, list(g))3、文本处理
3.1、re
作用:正则表达式。
import rem = re.search(r'(\d{4})-(\d{2})', '2025-08')m.group(1) # '2025're.sub(r'\s+', ' ', text) # 压缩空格3.2、string / textwrap / unicodedata
作用:
string提供常量和简单工具处理 ASCII 文本textwrap负责按宽度优雅地换行与缩进多行文本unicodedata让你查询和转换 Unicode 字符的规范化形式与属性。
import string, textwrap, unicodedatastring.ascii_letters # 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'textwrap.fill(s, width=40) # 自动换行unicodedata.name('A') # 'LATIN CAPITAL LETTER A'4、二进制 & 编码
4.1、struct
作用:在 bytes 与 C 结构体之间转换。
import structstruct.pack('>hhl', 1, 2, 3) # 打包成字节struct.unpack('f', b'\x40\x49\x0f\xdb')[0] # 解包 float4.2、base64 / binascii / codecs
作用:
base64用可打印 ASCII 编解码二进制binascii在二进制与十六进制(及 Base64/32/16)间快速转换并校验校验和codecs注册并流式处理各种文本编码的编解码与增量转换。
import base64, codecsbase64.b64encode(b'binary') # b'YmluYXJ5'codecs.encode('hello', 'rot_13') # 'uryyb'5、文件 & 目录 I/O
5.1、os / os.path / pathlib
作用:操作系统接口与路径。
import os, pathlibos.listdir('.')pathlib.Path('foo/bar').mkdir(parents=True, exist_ok=True)os.path.join('root', 'file.txt')5.2、shutil
作用:高级文件操作(复制、打包、删除树)。
import shutilshutil.copy('src.py', 'dst.py')shutil.make_archive('proj', 'zip', root_dir='.')5.3、glob / fnmatch
作用:文件通配符匹配。
import globglob.glob('*.py') # 当前目录所有 py6、进程 & 并发
6.1、subprocess
作用:启动子进程并与其通信。
import subprocessout = subprocess.check_output(['ls', '-l'])subprocess.run(['python', '-m', 'pip', 'install', 'tqdm'])6.2、threading / concurrent.futures
作用:线程与线程池。
from concurrent.futures import ThreadPoolExecutorwith ThreadPoolExecutor() as ex: ex.map(download, urls)6.3、multiprocessing
作用:多进程并行,绕过 GIL。
from multiprocessing import Poolwith Pool() as p: p.map(cpu_intensive, data)7、日期 & 时间
7.1、datetime / time / calendar
作用:日期时间运算、格式化、本地化。
from datetime import datetime, timedeltanow = datetime.now()(now + timedelta(days=7)).strftime('%Y-%m-%d %H:%M')8、数学 & 统计
8.1、math / cmath
作用:浮点数学(math)与复数(cmath)。
import mathmath.sqrt(2); math.isclose(0.1+0.2, 0.3)8.2、random / secrets
作用:伪随机与安全随机。
import random, secretsrandom.choice(['♠','♥','♦','♣'])secrets.token_hex(16) # 32 位安全令牌8.3、decimal / fractions / statistics
作用:高精度十进制、分数、统计量。
from decimal import DecimalDecimal('0.1') + Decimal('0.2') # Decimal('0.3')from statistics import mean, medianmean([1,2,3,4])9、数据序列化 & 持久化
9.1、json / csv / configparser
作用:轻量结构化数据交换。
import json, csvjson.dumps(obj, ensure_ascii=False, indent=2)with open('data.csv') as f: for row in csv.DictReader(f): print(row)9.2、pickle / shelve / sqlite3
作用:二进制对象持久化、嵌入式数据库。
import pickle, sqlite3pickle.dump(obj, open('cache.pkl', 'wb'))conn = sqlite3.connect('demo.db')conn.execute('CREATE TABLE IF NOT EXISTS user(id INTEGER PRIMARY KEY, name TEXT)')10、网络 & 互联网
10.1、urllib / http.client / smtplib / email
作用:HTTP 请求、构造邮件等。
from urllib.request import urlopenhtml = urlopen('https://example.com').read().decode()10.2、socket / ssl
作用:底层网络通信与安全套接字。
import socket, sslctx = ssl.create_default_context()with ctx.wrap_socket(socket.socket(), server_hostname='pypi.org') as s: s.connect(('pypi.org', 443))11、调试 & 性能测试
11.1、logging
作用:标准日志系统,分级、可配置。
import logginglogging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')logging.info('Started')11.2、pdb / cProfile / timeit
作用:交互式调试、性能分析、小段代码计时。
python -m pdb script.pypython -m cProfile -s cumulative script.pyimport timeittimeit.timeit('sum(range(1000))', number=10000)