You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本指定类注释功能实现方案(排除all_results类)

问题描述

我的脚本文件包含大量类,代码示例如下:

def func1():
  ...

class IPSEC(aetest.Testcase):
  ....

class IPSEC_DPI(aetest.Testcase):
  ....

class IPSEC_FNF(aetest.Testcase):
  ....
   .
   .
more classes
   .
   .
class all_results(aetest.Testcase):
  ....

其中all_results是最后一个类。我需要实现一个函数,接收类名和脚本文件路径,将指定类注释掉,但all_results类永远不能被注释。我自己写了下面的函数,但执行失败,请问有没有更简洁的实现方法?

def comment_lines(file_name, profile):
    lines = open(file_name, 'r').readlines()
    start=None
    end=None
    i=0
    print(f"looking for class {profile}(aetest.Testcase):")
    for i in range(0, len(lines)):
        if f"class {profile}(aetest.Testcase):" in lines[i]:
            start=i
            break
        i+=1
    for i in range(start+1, len(lines)):
        if f"class " in lines[i]:
            end=i-2
            break
        i+=1
    for i in range(start, end+1):
        lines[i] = "#" + lines[i]
    out = open(file_name, 'w')
    out.writelines(lines)
    out.close()

解决方案

原函数的问题

  1. 循环中手动i+=1和range遍历逻辑冲突,导致索引混乱
  2. 类结束位置的计算(end=i-2)完全依赖固定偏移,容易出现漏注释或多注释的情况
  3. 未对all_results类做保护判断,存在误操作风险
  4. 未使用上下文管理器处理文件,可能出现资源泄漏

更简洁的实现

直接按行扫描,通过标记跟踪目标类的代码块,同时跳过保护类:

def comment_class(file_path, target_class):
    # 直接跳过保护类的注释请求
    if target_class == "all_results":
        print("all_results类不允许被注释")
        return
    
    in_target_class = False
    modified_lines = []
    
    # 用上下文管理器自动处理文件开闭
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            stripped_line = line.strip()
            # 匹配目标类定义行,开启注释标记
            if stripped_line == f"class {target_class}(aetest.Testcase):":
                in_target_class = True
                modified_lines.append(f"# {line}")
                continue
            # 遇到新的类定义,关闭注释标记
            elif in_target_class and stripped_line.startswith("class "):
                in_target_class = False
            
            # 根据标记决定是否添加注释符号
            modified_lines.append(f"# {line}" if in_target_class else line)
    
    # 写入修改后的内容
    with open(file_path, 'w', encoding='utf-8') as f:
        f.writelines(modified_lines)

实现说明

  • 用with上下文管理器确保文件自动关闭,避免资源泄漏
  • 通过in_target_class标记精准跟踪目标类的代码范围,无需计算索引偏移
  • 直接拦截all_results类的操作请求,符合需求
  • 保留原文件的换行、缩进格式,不会破坏代码结构

内容的提问来源于stack exchange,提问作者Akshay J

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 20:25:23