Okay, I understand. You need the script to be able to handle a specific error message that might appear on the second line (index 1 in a zero-based list of lines). If that message is present, the actual data lines (proc, prog_name inproc iter, and the subsequent key-value pairs) will be shifted down by one line.
Here's the updated Python script that incorporates this logic:
python
import os
import re
import json # Added for cleaner output
# Specific error message to ignore if present on the second line (index 1 in cleaned lines)
ERROR_LINE_CONTENT = "cp: cannot create regular file '/tmp/checkpoint-fsync': File exists"
# List to store all parsed dictionaries
all_data = []
# Process each .out file in the current directory
for filename in os.listdir('.'):
if filename.endswith('.out'):
filepath = os.path.join('.', filename) # Use full path for open
print(f"Processing {filename}...") # Added for clarity during execution
try:
with open(filepath, 'r') as f:
raw_lines = f.readlines()
# Strip whitespace from lines and filter out empty lines
# This makes line indexing simpler as we only deal with non-empty, stripped lines
cleaned_lines = [line.strip() for line in raw_lines if line.strip()]
# Ensure minimum lines required for basic parsing after cleaning
# We need at least:
# - line 0: program name (make: ...)
# - line 1: proc OR error message
# - line 2: prog_name inproc iter OR proc (if error was on line 1)
# So, we need at least 3 non-empty lines in `cleaned_lines`.
if len(cleaned_lines) < 3:
print(f"Skipping {filename}: insufficient non-empty lines ({len(cleaned_lines)}). Need at least 3.")
continue
# --- Parse Line 0 (cleaned_lines[0]): Program Name ---
match = re.search(r"'(.*?)'", cleaned_lines[0])
if not match:
print(f"Skipping {filename}: invalid first line format (program name not found in '{cleaned_lines[0]}').")
continue
program_name = match.group(1)
print(f" Program name: {program_name}")
# --- Check for Error Line on cleaned_lines[1] and determine line indices ---
# These indices refer to the `cleaned_lines` list
has_error_line = False
# Check if there is a second cleaned line and if it contains the error string
# len(cleaned_lines) > 1 is already guaranteed by the len < 3 check
if ERROR_LINE_CONTENT in cleaned_lines[1]:
has_error_line = True
# If error is on cleaned_lines[1], proc is on cleaned_lines[2], details on cleaned_lines[3]
proc_line_index = 2
prog_details_line_index = 3
data_start_line_index = 4
print(f" Found error line at cleaned line index 1. Adjusting expected data indices.")
else:
# If no error on cleaned_lines[1], proc is on cleaned_lines[1], details on cleaned_lines[2]
proc_line_index = 1
prog_details_line_index = 2
data_start_line_index = 3
print(f" No error line found at cleaned line index 1. Using default data indices.")
# Ensure required subsequent lines exist based on the determined indices
# We need lines up to prog_details_line_index to exist in `cleaned_lines`
# i.e., the index `prog_details_line_index` must be less than the length
if len(cleaned_lines) <= prog_details_line_index:
print(f"Skipping {filename}: insufficient non-empty lines after checking for error. Need at least {prog_details_line_index + 1} non-empty lines but only found {len(cleaned_lines)}.")
continue
# --- Parse Proc Line (at proc_line_index in cleaned_lines) ---
# Access cleaned_lines[proc_line_index] is safe due to the previous length check
proc_str = cleaned_lines[proc_line_index]
try:
proc = int(proc_str)
print(f" Parsed proc: {proc}")
except ValueError:
# ValueError means the line content wasn't a valid integer
print(f"Skipping {filename}: invalid 'proc' value. Expected integer at cleaned line index {proc_line_index}, found '{cleaned_lines[proc_line_index]}'.")
continue
# --- Parse Program Details Line (at prog_details_line_index in cleaned_lines) ---
# Access cleaned_lines[prog_details_line_index] is safe due to the previous length check
prog_details_line = cleaned_lines[prog_details_line_index]
parts = prog_details_line.split()
# Basic check: does it start with the program name?
# Use a stricter check: first part must match program_name exactly and there must be at least 3 parts
if len(parts) < 3 or parts[0] != program_name:
print(f"Skipping {filename}: expected program details line (starting with '{program_name}' and having at least 3 parts) not found or incorrect format at cleaned line index {prog_details_line_index}. Found '{cleaned_lines[prog_details_line_index]}'.")
continue
try:
inproc = int(parts[1])
iter_val = int(parts[2])
print(f" Parsed inproc: {inproc}, iter: {iter_val}")
except ValueError:
print(f"Skipping {filename}: invalid 'inproc' or 'iter' value at cleaned line index {prog_details_line_index}. Expected integers in '{parts[1]} {parts[2]}'.")
continue
# --- Initialize the dictionary for this file ---
data = {
'program': program_name,
'proc': proc,
'inproc': inproc,
'iter': iter_val
}
# --- Parse remaining lines for key-value pairs ---
# Iterate from the line index where data lines are expected to start in cleaned_lines
# Ensure there are lines remaining to process from data_start_line_index onwards
if len(cleaned_lines) > data_start_line_index:
print(f" Parsing data lines starting from cleaned line index {data_start_line_index}...")
for line in cleaned_lines[data_start_line_index:]:
if ':' in line:
key, val_part = line.split(':', 1)
key = key.strip()
# Extract the first numeric token from the value part
val_tokens = val_part.strip().split()
if val_tokens:
val_str = val_tokens[0]
try:
val_num = float(val_str)
# Store the value using the extracted key
data[key] = val_num
# print(f" Found data: {key}: {val_num}") # Optional: uncomment for detailed parsing trace
except ValueError:
# If the first token isn't a number, ignore it as per requirements
# print(f" Skipping non-numeric value for key '{key}': '{val_tokens}'") # Optional trace
pass # Skip non-numeric values
# Add the completed dictionary to the list
all_data.append(data)
print(f"Successfully parsed data from {filename}.")
except FileNotFoundError:
print(f"Error: File not found - {filename}")
except Exception as e:
print(f"An unexpected error occurred while processing {filename}: {e}")
import traceback
traceback.print_exc() # Print detailed error info
# Output the collected data (for demonstration)
print("\n--- Collected Data ---")
if all_data:
# Use json.dumps for pretty printing the list of dictionaries
print(json.dumps(all_data, indent=4))
else:
print("No data collected from any files.")
Key Changes:
ERROR_LINE_CONTENT Constant: Defines the exact string to look for.
cleaned_lines: Reads all lines, strips whitespace from both ends, and filters out any lines that become empty after stripping. This simplifies line indexing.
Error Check at Index 1: After cleaning, the script checks if cleaned_lines[1] exists and contains the ERROR_LINE_CONTENT.
Dynamic Indexing: Based on whether the error line is found, it sets the expected indices for the proc line (proc_line_index), the prog_name inproc iter line (prog_details_line_index), and the start of the subsequent key-value lines (data_start_line_index).
Robust Index Access: Added checks (len(cleaned_lines) <= required_index) before attempting to access lines using the determined indices to prevent IndexError if a file is shorter than expected for a given structure.
Improved Error Handling: Added more specific print statements to indicate why a file is being skipped (e.g., invalid format, missing data). Included a general except Exception with traceback for debugging unexpected errors.
JSON Output: Used json.dumps to print the final list of dictionaries in a human-readable, structured format.
This script will now correctly parse files whether or not that specific error message is present on the second non-empty line.