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

Python正则提取测试日志中指定首尾模式的内容(含首尾)

Extract Log Segments with Exact Start/End Boundaries (Including Matchers)

Let's fix your script to correctly pull the log segments you need—including both the full start line (from --- /b/act-builder/sandboxes/ through Linux ---) and the Error code end marker, while supporting multiple matches across the entire log file.

What Was Wrong With Your Original Code

Your approach had two critical gaps:

  1. The regex only captured content after /b/act-builder/ (thanks to the capturing group (.*?)), so it cut off the full start line and excluded the Error code marker entirely.
  2. It didn't account for the Linux --- suffix that ends your target starting line.

Corrected Solution

Here's a revised script that fixes these issues and follows Python best practices for file handling:

import re

# Use a `with` statement to safely open/close the file automatically
with open('atf_log_28378.txt', 'r') as file:
    log_content = file.read()

# Regex pattern tailored to your requirements:
# - Matches lines starting with your exact prefix
# - Includes all content up to and including "Error code"
# - Works across multiple lines
pattern = r'^--- /b/act-builder/sandboxes/.*?Linux ---.*?Error code'
matched_segments = re.findall(pattern, log_content, re.MULTILINE | re.DOTALL)

# Print each matched segment with a clear label
for count, segment in enumerate(matched_segments, 1):
    print(f'Failed Test Case #{count}:\n{segment}\n')

Regex Breakdown

Let's break down why this pattern works:

  • ^--- /b/act-builder/sandboxes/: Explicitly matches the start of a line with your required prefix (the ^ works with re.MULTILINE to target every line start, not just the top of the file)
  • .*?Linux ---: Non-greedily grabs all content until it hits the Linux --- end of your starting line
  • .*?Error code: Non-greedily captures everything between the start line and the Error code marker, including newlines (thanks to re.DOTALL)
  • re.MULTILINE | re.DOTALL: Combined flags let the regex handle line breaks and multi-line segments correctly

Example Output

For your sample input line:

--- /b/act-builder/sandboxes/ACT-SB-RELEASE_174_THROTTLE-28378/src/junos/usr.sbin/rpd/lib/policy/atf-tests.host,linux --- *** [atf-run.log] Error code

The script will output:

Failed Test Case #1:
--- /b/act-builder/sandboxes/ACT-SB-RELEASE_174_THROTTLE-28378/src/junos/usr.sbin/rpd/lib/policy/atf-tests.host,linux --- *** [atf-run.log] Error code

If your log has multiple matching segments, each will be printed as a separate labeled entry.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:07:09