Python 3 - Carbide Create Pro - GCode Splitter

Folks I have felt there has to be a better way to split my GCode before I run it, I have spent a few nights with my new developer (chat gpt) debugging my bad python to come up with this script that will take a Carbide Create Pro GCode file and split it into each of its tool paths, leave the work piece info at the top and remove the M6/M03 commands.

I left the M05 commands as they don’t hurt anything.

Here is the code:

import sys
print(sys.argv[1])
origFile = sys.argv[1]

# Set this variable to 0 to keep "M6" and "M03" lines, and 1 to remove them
remove_M6_M03 = 1

fd = open(origFile, "r")
lines = fd.readlines()
fd.close()

# Extract the first 8 lines
header_lines = lines[:8]

toolpaths = {}  # Dictionary to store the file objects for each toolpath

current_toolpath = None
for line in lines:
    if line.startswith("(Toolpath: "):  # Identify the start of a new toolpath
        if current_toolpath is not None:
            # Add M05 and M02 to the end of the previous toolpath
            if not lines[-2].startswith(("M05", "M02")):
                toolpaths[current_toolpath].write("M05\n")
            toolpaths[current_toolpath].write("M02\n")
            toolpaths[current_toolpath].close()
        toolpath_name = line.split("(Toolpath: ")[1].split(")")[0]
        new_file_name = origFile[0:-3] + "_" + toolpath_name + ".nc"
        toolpaths[toolpath_name] = open(new_file_name, "w")
        current_toolpath = toolpath_name
        # Write the first 8 lines to the current split file
        for header_line in header_lines:
            toolpaths[current_toolpath].write(header_line)
    if current_toolpath is not None:
        # Skip writing lines starting with "M6" or "M03" based on the variable
        if remove_M6_M03 and line.startswith(("M6", "M03")):
            continue
        toolpaths[current_toolpath].write(line)

# Add M05 and M02 to the last toolpath
if current_toolpath is not None:
    if not lines[-2].startswith(("M05", "M02")):
        toolpaths[current_toolpath].write("M05\n")
    toolpaths[current_toolpath].write("M02\n")
    toolpaths[current_toolpath].close()

# Close all the files
for file_obj in toolpaths.values():
    file_obj.close()

I named my python file avc.py and then run my NC file though it like this.

python3 avc.py coinsplit.nc

I hope this helps someone!

1 Like

You may wish to check out Fenrus’ Gcode splitter

I have used this tool, but it does not always split correctly anymore.

Does it work?? That’s the important thing if it does. It’s not how i would have done it. What if you’re file isn’t array 1?
I would have done it more like this.
origFile=input(“where’s it at yo’”)

You also should have a section for the footer like you have for the header so it knows the code is over