请设计一个Python脚本,用于检查项目中所有文件的导入语句是否符合PEP 8的分组和顺序规范,并输出不符合的文件和具体问题。

import os
import re
from collections import defaultdict

def check_imports_in_file(file_path):
    """检查文件的导入语句是否符合PEP 8规范"""
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.readlines()
    
    issues = []
    current_group = None
    last_import_line = -1
    
    # PEP 8 导入分组顺序:标准库 > 第三方库 > 本地库
    groups_order = ['standard', 'third_party', 'local']
    groups_pattern = {
        'standard': r'^import \w+$|^from \w+ import \w+$',
        'third_party': r'^import \w+\.\w+$|^from \w+\.\w+ import \w+$',
        'local': r'^import \w+\.\w+\.\w+$|^from \w+\.\w+\.\w+ import \w+$'
    }
    
    for idx, line in enumerate(content):
        line = line.strip()
        if line.startswith('import ') or line.startswith('from '):
            for group_name, pattern in groups_pattern.items():
                if re.match(pattern, line):
                    if current_group is None:
                        current_group = group_name
                    elif groups_order.index(group_name) < groups_order.index(current_group):
                        issues.append(f"Line {idx + 1}: 导入分组顺序错误 (当前组: {current_group}, 预期组: {group_name})")
                    elif group_name != current_group:
                        issues.append(f"Line {idx + 1}: 导入语句应该属于 {current_group} 组")
                    break
            if last_import_line != -1 and idx != last_import_line + 1:
                issues.append(f"Line {idx + 1}: 导入语句之间应该有且仅有一个空行")
            last_import_line = idx
    
    return issues


def check_project_imports(project_dir):
    """检查项目中所有文件的导入语句"""
    issues = defaultdict(list)
    for root, _, files in os.walk(project_dir):
        for file in files:
            if file.endswith('.py'):
                file_path = os.path.join(root, file)
                file_issues = check_imports_in_file(file_path)
                if file_issues:
                    issues[file_path] = file_issues
    return issues


def report_issues(issues):
    """输出不符合规范的文件和问题"""
    if not issues:
        print("所有文件的导入语句均符合PEP 8规范。")
    else:
        for file_path, file_issues in issues.items():
            print(f"文件: {file_path}")
            for issue in file_issues:
                print(f"  - {issue}")


if __name__ == "__main__":
    project_directory = input("请输入项目目录路径: ")
    import_issues = check_project_imports(project_directory)
    report_issues(import_issues)

代码说明

  1. check_imports_in_file函数:

    • 用于检查单个文件的导入语句是否符合PEP 8规范。
    • 导入语句分为三组:标准库(standard)、第三方库(third_party)和本地库(local)。
    • 检查导入语句的分组顺序是否正确(标准库在前,本地库在后)。
    • 检查导入语句之间是否有空行分隔。
  2. check_project_imports函数:

    • 遍历项目目录中的所有Python文件,并调用check_imports_in_file函数检查每个文件。
    • 使用字典收集所有不符合规范的文件及其问题。
  3. report_issues函数:

    • 输出不符合规范的文件列表及具体问题。
  4. 主程序:

    • 用户输入项目目录路径,调用上述函数完成检查并输出结果。

示例

假设项目目录结构如下:

project/
    ├── main.py
    ├── utils/
    │   ├── helper.py
    │   └── __init__.py
  • 不符合规范的导入语句:
    • helper.py中先导入本地库,再导入标准库。
    • main.py中导入语句之间没有空行分隔。

运行脚本后,输出可能如下:

文件: project/main.py
  - Line 5: 导入语句之间应该有且仅有一个空行
文件: project/utils/helper.py
  - Line 2: 导入分组顺序错误 (当前组: local, 预期组: standard)