可行但需显式安装配置:必须安装兼容版本pytest-flake8==1.1.1,通过pytest.ini配置addopts = --flake8启用,且规则配置须放在.flake8或setup.cfg的[flake8]段下,pyproject.toml中[tool.flake8]不被识别。

直接在 pytest 中跑 flake8 检查是可行的,但默认不启用——必须显式安装插件并配置,否则 pytest 完全忽略代码风格问题。
安装 pytest-flake8 并确认版本兼容性
这个插件已多年未维护,pytest-flake8==1.1.1 是最后一个支持 Python 3.8+ 和 pytest 7+ 的稳定版。装错版本会导致 ImportError: cannot import name 'main' 或静默失效。
- 运行
pip install pytest-flake8==1.1.1(不要用latest) - 检查是否生效:
pytest --help | grep flake8—— 应看到--flake8选项 - 若提示
unknown option,说明插件未加载,大概率是版本不匹配或安装到错误 Python 环境
启用 flake8 检查的三种方式(推荐 pytest.ini)
命令行临时启用最简单,但团队协作必须固化到配置文件;pyproject.toml 对该插件支持不稳定,容易被忽略,优先用 pytest.ini。
- 命令行:直接加
--flake8,例如pytest tests/ --flake8 -
pytest.ini(推荐):在项目根目录新建,内容为[tool:pytest] addopts = --flake8
-
pyproject.toml(慎用):部分环境会跳过 flake8 配置,如必须用,写成[tool.pytest.ini_options] addopts = ["--flake8"]
自定义 flake8 规则和排除路径
插件默认读取项目根目录下的 .flake8 或 setup.cfg,但不会自动继承 pyproject.toml 中的 [flake8] 配置段——这是最常被踩的坑。
- 在
.flake8中写[flake8] ignore = E501, W503 exclude = .git,__pycache__,migrations
- 如果用
setup.cfg,section 必须叫[flake8],不是[tool.flake8] -
--flake8-ignore命令行参数仅覆盖 ignore 列表,不能新增规则;想临时跳过某目录,用--flake8-max-line-length=88这类参数更可靠
注意:pytest-flake8 不支持 per-file-ignores,也不识别 pyproject.toml 的 flake8 配置块。只要发现规则没生效,第一反应应检查配置文件名和位置,而不是怀疑代码本身。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











