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

求助:将含grep的Bash命令逻辑转换为Python脚本

将Bash命令逻辑转换为Python脚本

需求说明

核心逻辑是:在指定目录及其所有子文件夹中,查找包含TEST_F(的文本行,并提取TEST_F(之后的对应部分;同时获取格式为YYYY-MM-DD的当前日期。

原始Bash命令

ls
ls *
TODAY=`date +%Y-%m-%d`
cd xx/xx/autotests/
grep -R "TEST_F(" | sed s/"TEST_F("/"#"/g | cut -f2 -d "#" | while read LINE

你编写的Python代码(存在问题)

import fnmatch
import os
from datetime import datetime

time = datetime.now()

dir_path = "/xx/xx/autotests"
dirs = os.listdir(dir_path)
TODAY = time.strftime("%Y-%m-%d")

filesOfDirectory = os.listdir(dir_path)
print(filesOfDirectory)
pattern = "TEST_F("
for file in filesOfDirectory:
    if fnmatch.fnmatch(file, pattern):
        print(file)

问题分析

  • os.listdir()仅读取当前目录的文件/文件夹,无法递归遍历子目录
  • 代码错误地匹配文件名是否包含TEST_F(,而非需求中的文件内容
  • 未实现提取TEST_F(之后内容的核心逻辑

正确的Python实现

import os
from datetime import datetime

# 获取当前日期,与Bash格式一致
TODAY = datetime.now().strftime("%Y-%m-%d")
# 指定目标目录
target_dir = "/xx/xx/autotests"

# 递归遍历目标目录下的所有文件
for root, _, files in os.walk(target_dir):
    for file in files:
        file_path = os.path.join(root, file)
        # 跳过非文件类型(os.walk返回的files已过滤目录,此处做冗余校验)
        if not os.path.isfile(file_path):
            continue
        # 逐行读取并处理文件内容
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                for line in f:
                    line = line.strip()
                    if "TEST_F(" in line:
                        # 模拟Bash中sed+cut的逻辑:替换后分割提取目标部分
                        processed_line = line.replace("TEST_F(", "#")
                        parts = processed_line.split("#", 1)
                        if len(parts) >= 2:
                            extracted_content = parts[1].strip()
                            print(extracted_content)
        except UnicodeDecodeError:
            print(f"跳过无法读取的二进制/编码异常文件: {file_path}")
        except Exception as e:
            print(f"处理文件{file_path}时出错: {str(e)}")

代码说明

  • os.walk(target_dir):递归遍历目标目录的所有层级,返回当前目录路径、子目录列表、文件列表
  • with open(...):安全读取文件,自动管理文件句柄的打开与关闭
  • line.replace("TEST_F(", "#").split("#", 1):完全对齐Bash脚本中sed替换+cut分割的逻辑,精准提取目标内容
  • 异常处理:应对二进制文件、编码错误等场景,避免脚本意外中断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:10:41