#!/usr/bin/env python3 import sys import os def modify_gcode(input_file): # Generate the output file name by appending "_modded" to the input file name base, ext = os.path.splitext(input_file) output_file = f"{base}_modded{ext}" # Read the contents of the G-code file with open(input_file, 'r') as file: lines = file.readlines() # Buffer to store the additional commands buffer = [] # First Pass: Identify and extract lines between G0 and the first G4, add M5 i = 0 while i < len(lines): line = lines[i].strip() if line.startswith("G0") and "X" in line and "Y" in line: # Detect G0 X??.? Y??.? if i + 1 < len(lines) and lines[i + 1].strip() == "G92 Z0.": # Check for G92 Z0. immediately after temp_buffer = [] temp_buffer.append(line) # Add G0 line temp_buffer.append(lines[i + 1].strip()) # Add G92 line i += 2 while i < len(lines) and not lines[i].strip().startswith("G4"): # Collect until G4 temp_buffer.append(lines[i].strip()) i += 1 if i < len(lines): # Include the G4 line temp_buffer.append("G4 P2.0") temp_buffer.append("M5\nG0 Z30.0\nG4 P5.0 (Cool Down)\n") # Add M5 after the sequence buffer.extend(temp_buffer) i += 1 # Append the additional commands to the buffer buffer.append("G4 P30.0") # Second Pass: Insert buffer after the first H0 line while keeping all original lines with open(output_file, 'w') as file: inserted = False for line in lines: file.write(line) if not inserted and line.startswith("H0"): file.write("\n\n(Pierce the stock only, change to a fresh tip later for the actual cuts)\n\n") file.write("\n".join(buffer) + "\n") inserted = True print(f"Modified file written to: {output_file}") # Entry point for the script if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: python3 modify_gcode.py ") sys.exit(1) input_file = sys.argv[1] if not os.path.exists(input_file): print(f"Error: File '{input_file}' not found.") sys.exit(1) modify_gcode(input_file)