修改这个脚本,使它保存结果到同一个文件,而不是一堆小文件
- User
修改这个脚本,使它保存结果到同一个文件,而不是一堆小文件
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
修改这个脚本,使它保存结果到同一个文件,而不是一堆小文件
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
好的,我将修改脚本,使其将所有处理结果保存到同一个文件中,而不是为每个输入文件创建单独的输出文件。以下是修改后的脚本:
import subprocess
import os
from pathlib import Path
import time
import sys
# --- Configuration ---
LIST_FILE = "./bc_files_absolute.list"
LRSAN_EXECUTABLE = "./build/lib/lrsan"
OUTPUT_FILE = "lrsan_results_combined.txt" # 单个输出文件
ERROR_FILE = "lrsan_errors_combined.txt" # 单个错误文件
# ---------------------
def load_file_list(list_file_path):
"""Loads the list of BC files from the specified file."""
if not os.path.exists(list_file_path):
print("Error: Input list file not found: {}".format(list_file_path))
return []
with open(list_file_path, 'r') as f:
# Read lines, strip whitespace, and ignore empty lines
files = [line.strip() for line in f if line.strip()]
return files
def process_bc_file(bc_file_path, output_file, error_file):
"""
Runs the lrsan command on a single BC file and appends the output to the combined files.
"""
# 1. Validate input file existence
if not os.path.exists(bc_file_path):
print(" [SKIP] BC file not found: {}".format(bc_file_path))
return False
# 2. Get the base filename for logging
input_path = Path(bc_file_path)
base_name = input_path.name
# 3. Construct the command
command = [LRSAN_EXECUTABLE, "-lrc", bc_file_path]
print(" Running: {}".format(' '.join(command)))
start_time = time.time()
try:
# 4. Execute the command
result = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True
)
# Manually decode the output from bytes
stdout_decoded = result.stdout.decode('utf-8', errors='ignore')
# 5. Append successful output to the combined output file
with open(output_file, 'a', encoding='utf-8') as out_f:
out_f.write("\n\n=== Results for: {} ===\n".format(base_name))
out_f.write("Command: {}\n".format(' '.join(command)))
out_f.write("Timestamp: {}\n".format(time.strftime("%Y-%m-%d %H:%M:%S")))
out_f.write("Duration: {:.2f} seconds\n".format(time.time() - start_time))
out_f.write("=" * 50 + "\n")
out_f.write(stdout_decoded)
out_f.write("\n" + "=" * 50 + "\n")
duration = time.time() - start_time
print(" [SUCCESS] Results appended to {} (Took {:.2f}s)".format(OUTPUT_FILE, duration))
return True
except subprocess.CalledProcessError as e:
# 6. Handle command failure
duration = time.time() - start_time
print(" [ERROR] Command failed for {} with return code {} (Took {:.2f}s)".format(
base_name, e.returncode, duration))
# Decode the output from bytes
stdout_decoded = e.stdout.decode('utf-8', errors='ignore') if e.stdout else "[No stdout]"
stderr_decoded = e.stderr.decode('utf-8', errors='ignore') if e.stderr else "[No stderr]"
# Append error details to the combined error file
with open(error_file, 'a', encoding='utf-8') as err_f:
err_f.write("\n\n=== Error for: {} ===\n".format(base_name))
err_f.write("Command: {}\n".format(' '.join(command)))
err_f.write("Return Code: {}\n".format(e.returncode))
err_f.write("Timestamp: {}\n".format(time.strftime("%Y-%m-%d %H:%M:%S")))
err_f.write("Duration: {:.2f} seconds\n".format(duration))
err_f.write("=" * 50 + "\n")
err_f.write("--- STDOUT ---\n")
err_f.write(stdout_decoded)
err_f.write("\n--- STDERR ---\n")
err_f.write(stderr_decoded)
err_f.write("\n" + "=" * 50 + "\n")
print(" Error details appended to {}".format(ERROR_FILE))
return False
except FileNotFoundError:
print("\n[CRITICAL ERROR] LRSAN executable not found at: {}".format(LRSAN_EXECUTABLE))
print("Please check the LRSAN_EXECUTABLE path in the script.")
sys.exit(1)
def main():
# Initialize output files (clear existing content)
with open(OUTPUT_FILE, 'w', encoding='utf-8') as f:
f.write("=== LRSan Combined Results ===\n")
f.write("Generated on: {}\n".format(time.strftime("%Y-%m-%d %H:%M:%S")))
f.write("=" * 50 + "\n")
with open(ERROR_FILE, 'w', encoding='utf-8') as f:
f.write("=== LRSan Combined Errors ===\n")
f.write("Generated on: {}\n".format(time.strftime("%Y-%m-%d %H:%M:%S")))
f.write("=" * 50 + "\n")
bc_files = load_file_list(LIST_FILE)
total_files = len(bc_files)
if not total_files:
print("No files to process. Exiting.")
return
print("--- Starting LRSan Batch Processing ---")
print("Total files found: {}".format(total_files))
print("LRSan tool: {}".format(LRSAN_EXECUTABLE))
print("Output file: {}".format(os.path.abspath(OUTPUT_FILE)))
print("Error file: {}".format(os.path.abspath(ERROR_FILE)))
print("---------------------------------------\n")
success_count = 0
failed_count = 0
for index, bc_file_path in enumerate(bc_files):
print("Processing file {}/{}: {}".format(index + 1, total_files, Path(bc_file_path).name))
success = process_bc_file(bc_file_path, OUTPUT_FILE, ERROR_FILE)
if success:
success_count += 1
else:
failed_count += 1
print("-" * 40)
print("\n--- Summary ---")
print("Total processed: {}".format(total_files))
print("Successful: {}".format(success_count))
print("Failed/Skipped: {}".format(failed_count))
print("All results saved to: {}".format(OUTPUT_FILE))
print("All errors saved to: {}".format(ERROR_FILE))
print("Processing finished.")
if __name__ == "__main__":
# Check Python version just in case
if sys.version_info < (3, 5):
print("This script requires Python 3.5 or newer.")
sys.exit(1)
main()
单个输出文件:
lrsan_results_combined.txt 文件中单个错误文件:
lrsan_errors_combined.txt 文件中格式改进:
=====)使输出更易读保持兼容性:
.format() 方法而不是 f-stringsrun_lrsan_batch_single_output.py./bc_files_absolute.list 和 ./build/lib/lrsan 存在python3 run_lrsan_batch_single_output.pylrsan_results_combined.txt - 所有成功处理的结果lrsan_errors_combined.txt - 所有错误信息这样修改后,您只需要处理两个文件而不是大量的小文件,这使得结果的管理和查看更加方便。