Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import re
- import sys
- def postprocess_gcode(filename):
- """
- Postprocesses a G-code file to move estimated printing time lines
- before the EXECUTABLE_BLOCK_START marker, preserving original line endings.
- """
- try:
- with open(filename, 'rb') as f: # Open in binary read mode
- binary_content = f.read()
- except FileNotFoundError:
- print(f"Error: File '{filename}' not found.")
- return False
- except Exception as e:
- print(f"Error reading file '{filename}': {e}")
- return False
- # Try to decode using UTF-8; G-code is often ASCII, which is UTF-8 compatible.
- # If other encodings are possible, this might need to be more flexible.
- try:
- text_content = binary_content.decode('utf-8')
- except UnicodeDecodeError:
- try:
- # Fallback to latin-1 if UTF-8 fails, as it can decode any byte.
- # This might not render special characters correctly if they weren't originally latin-1.
- print(f"Warning: Could not decode '{filename}' as UTF-8. Attempting latin-1.")
- text_content = binary_content.decode('latin-1')
- except Exception as e:
- print(f"Error decoding file '{filename}': {e}")
- return False
- # Split lines, keeping the original line endings
- if not text_content: # Handle empty file
- lines = []
- else:
- lines = text_content.splitlines(keepends=True)
- # Patterns we're looking for (anchored to start of line string)
- time_pattern1 = re.compile(r'^; estimated printing time \(normal mode\) =')
- time_pattern2 = re.compile(r'^; estimated first layer printing time \(normal mode\) =')
- executable_pattern = re.compile(r'^; EXECUTABLE_BLOCK_START')
- # Store data about found lines
- time_lines_data = [] # List of tuples: (original_index, line_content_with_ending)
- executable_pos = -1
- first_executable_block_found = False
- for i, line_with_ending in enumerate(lines):
- if executable_pattern.match(line_with_ending):
- if not first_executable_block_found:
- executable_pos = i
- first_executable_block_found = True
- elif (time_pattern1.match(line_with_ending) or time_pattern2.match(line_with_ending)):
- if executable_pos != -1 and i > executable_pos:
- time_lines_data.append((i, line_with_ending))
- if executable_pos != -1 and time_lines_data:
- lines_to_insert_content = [line_content for _, line_content in time_lines_data]
- indices_to_delete = sorted([original_idx for original_idx, _ in time_lines_data], reverse=True)
- for index_to_delete in indices_to_delete:
- del lines[index_to_delete]
- # The executable_pos is the index in the 'lines' list *before* insertion.
- # If lines were deleted *before* executable_pos, its index would shift.
- # However, we only delete lines *after* executable_pos, so its index relative
- # to the start of the list remains correct for identifying the insertion point.
- current_insert_pos = executable_pos
- for line_content_with_ending in lines_to_insert_content:
- lines.insert(current_insert_pos, line_content_with_ending)
- current_insert_pos += 1
- # Join the lines back into a single string (original line endings are preserved)
- modified_text_content = "".join(lines)
- # Encode back to bytes using the initially successful (or fallback) encoding
- try:
- # Attempt to encode with UTF-8 first if that's what we decoded with
- # This assumes that if it decoded as UTF-8, it can be encoded back.
- # A more robust solution might store the detected encoding.
- # For simplicity, we'll try UTF-8, then latin-1 for encoding.
- try:
- output_binary_content = modified_text_content.encode('utf-8')
- except UnicodeEncodeError: # Should not happen if decoded as UTF-8 and no invalid chars added
- print(f"Warning: Could not encode modified content of '{filename}' as UTF-8. Attempting latin-1.")
- output_binary_content = modified_text_content.encode('latin-1')
- except Exception as e:
- print(f"Error encoding modified content for '{filename}': {e}")
- return False
- try:
- with open(filename, 'wb') as f: # Open in binary write mode
- f.write(output_binary_content)
- # print(f"File '{filename}' processed successfully, line endings preserved.")
- return True
- except Exception as e:
- print(f"Error writing to file '{filename}': {e}")
- return False
- else:
- # print(f"No relevant changes made to '{filename}'.")
- return True # Operation completed, even if no changes were made.
- sourceFile=sys.argv[1]
- postprocess_gcode(sourceFile)
Advertisement
Add Comment
Please, Sign In to add comment