PyCharm提交前Python代码规范轻量检查方案咨询
最优实现方案:用pre-commit框架
核心优势
- 不依赖IDE,所有团队成员提交代码时自动触发,避免PyCharm局部失效的问题
- 支持现成的代码检查工具,也能轻松自定义规则,满足团队扩展需求
- 可设置检查仅触发警告,完全不阻止提交流程
具体步骤
1. 安装pre-commit
直接用pip安装:
pip install pre-commit
2. 配置基础检查规则
在项目根目录创建.pre-commit-config.yaml文件,集成现成工具覆盖你的基础需求:
repos: # 用flake8检查方法长度、参数数量等规范 - repo: https://github.com/PyCQA/flake8 rev: 6.0.0 hooks: - id: flake8 args: # 自定义规则:方法最大参数4个,可按需调整其他参数 - "--max-args=4" - "--max-line-length=120" - "--max-complexity=10" # 设置为警告模式,不阻止提交 fail_fast: false stages: [commit]
3. 自定义检查新代码中的print语句
因为flake8默认不检查print语句,且你需要仅针对新提交的代码做检查,所以写一个本地自定义钩子:
在项目根目录创建scripts/check_new_print.py脚本:
import sys import subprocess def get_changed_py_lines(): # 获取本次提交改动的Python代码行 changed_files_result = subprocess.run( ["git", "diff", "--cached", "--name-only", "--diff-filter=ACM", "*.py"], capture_output=True, text=True ) changed_files = [f for f in changed_files_result.stdout.strip().split("\n") if f] if not changed_files: return [] changed_lines = [] for file in changed_files: diff_result = subprocess.run( ["git", "diff", "--cached", "-U0", file], capture_output=True, text=True ) for line in diff_result.stdout.split("\n"): # 只检查新增的代码行 if line.startswith("+") and not line.startswith("+++"): changed_lines.append((file, line[1:].strip())) return changed_lines def check_print_statements(): changed_lines = get_changed_py_lines() has_print = False for file, line in changed_lines: if "print(" in line: print(f"⚠️ 警告:{file}中新增了print语句:{line}") has_print = True # 返回0表示不阻止提交,即使有警告 return 0 if __name__ == "__main__": sys.exit(check_print_statements())
然后把这个自定义钩子加到.pre-commit-config.yaml里:
repos: # 上面的flake8配置... # 自定义print检查钩子 - repo: local hooks: - id: check-new-print name: Check new print statements entry: python scripts/check_new_print.py language: system files: \.py$ stages: [commit] # 强制不阻止提交 always_run: true pass_fast: false
4. 安装钩子到Git
在项目根目录运行:
pre-commit install
之后每次执行git commit时,pre-commit会自动运行所有配置的检查,有问题只会输出警告,不会中断提交流程。
5. 团队共享配置
把.pre-commit-config.yaml、scripts/check_new_print.py提交到仓库,其他成员拉取代码后,只需执行pre-commit install就能同步配置,统一检查规则。
扩展规则
如果后续团队要加新检查(比如禁止全局变量、检查注释覆盖率等),要么找现成的pre-commit钩子(比如pylint、mypy),要么像上面那样写自定义脚本即可,灵活性拉满。
内容的提问来源于stack exchange,提问作者Marko Zadravec
相关产品推荐
相关产品推荐

