r/pythonhelp • • Nov 07 '21

SOLVED I'm looking to speed up my g-code editor

I am currently writing a program to edit my g-code for my 3D printer I'm wanting the printer to move the print head out of the way of the print at the completion of every layer and then move back to position. The code that I have written works but it's taking a really long time for the code to go through the entire file. I've attached my g-code file with the code.

Any tips on better commenting code are appreciated as well.

file_name = "test_goproholder.gcode" # put your filename here z=0 newline=['\n']

with open(file_name, 'r+') as f:

new_code = ""            # where the new modified code will be put
content = f.readlines()  # gcode as a list where each element is a line

for line in content:
    gcode = line.strip('\n').split(" ")  # seperates the gcode from the comments
    try:                                 #searches for a Z layer height callout and sets our operator equal to the callout
        if 'Z'== gcode[4][0]:
            z = gcode[4][1:]
    except:
        if line.startswith(";LAYER:"):      #searches for a layer height callout
            insert1=[f'\nG0 X1 Y290 Z{float(z)+10}\n']
            insert2=['G4 P5000']
            gcode= gcode+insert1+insert2
    gcode=gcode+newline
    new_code+=''.join([str(element) for element in gcode])
    print(new_code)
print(z)
f.seek(0)
f.write(new_code)

Here's and example of my test code:

G1X66.43Y39.519E218.93118

F600 E-1

;LAYER_COUNT:56

;LAYER:0

M107

G0 F2625 X36.605 Y37.768 Z0.425

;TYPE:SKIRT

G1 F600 E0

G1 F900 X37.439 Y37.1 E0.03559

G1 X37.875 Y36.806 E0.05311

G1 X39.165 Y36.079 E0.10243

G1 X39.616 Y35.868 E0.11902

G1 X40.498 Y35.536 E0.15041

G1 X40.996 Y35.393 E0.16767

G0 X64.468 Y39.131

G0 X64.477 Y39.032

;TIME_ELAPSED:466.669759

;LAYER:1

M140 S60

M221 S100 T0

M106 S68

;MESH:

G0 F6562.5 X64.477 Y39.032 Z0.675

;TYPE:WALL-INNER

G1 F600 E218.89162

G1 F1800 X65.145 Y39.131 E218.90485

G1 X65.806 Y39.296 E218.9182

G1 X66.43 Y39.519 E218.93118

4 Upvotes

9 comments sorted by

2

u/Goobyalus Nov 08 '21

Strings are immutable in Python so every time you reassign with new_code += something, you are creating an entirely new, slightly bigger string, and throwing away the old object. I'm guessing this is probably your bottleneck.

Maintain a list of lines or objects and then join them at the end, or simply write output as you go instead of constructing a large string in memory.

You can also avoid reading the entire file into memory:

with open(file_name, "r") as f:
    for line in f:  # `f` is a generator of the lines in the file, so you can iterate over it
        ...

2

u/[deleted] Nov 09 '21

Great advice I ended up with the below code which runs much faster:

​ file_name = "Longtestfile.gcode" # put your filename here

Initializing my variables to be used

z=0 insert2='' i=0 #variable for counting lines of code

with open(file_name, 'r+') as f: #opening and reading the file

new_code = ""            # where the new modified code will be put
new_list=[]
content = f.readlines()  # gcode as a list where each element is a line

for line in content:
    i= i+1
    print(i)
    gcode = line.split(" ")  # seperates the gcode from the comments
    try:                                 #searches for a Z layer height callout and sets our operator equal to the callout
        if 'Z'== gcode[4][0]:
            z = gcode[4][1:]
            print(f"z is equal to {z}")
    except:
        if line.startswith(";LAYER:"):      #searches for a layer height callout
            insert1=[f'G0 X1 Y290 Z{float(z)+10}\nG4 P5000\n']
            new_list=new_list+[' '.join([str(element) for element in gcode])]+insert1
        else:
            new_list=new_list+[' '.join([str(element) for element in gcode])]
new_code=''.join([str(element) for element in new_list])
print(f"Here's the print out\n{new_code}")
with open(f'ed_{file_name}','w') as end:
    end.write(new_code)

I ended up adding the variable i to count the number of lines I read as a better method of understanding what line of code my program is reading. Overall this code reads %10,000 faster. Which is needed as the Gcode is 50,000+ lines of code.

1

u/Goobyalus Nov 09 '21 edited Nov 09 '21

FYI to format code properly opn Reddit, indent all lines by an extra 4 spaces (or tab the whole thing in your editor before copying). Edit: And leave blank lines on either side of the code block.


You can simplify the line index with enumerate. Here, I'm opening a file that contains your gcode snippet, and printing out the line number and the line contents:

>>> with open("temp2.txt", "r") as f:
...   for original_line_no, line in enumerate(f):
...     print(f"{original_line_no:02}:\t{line.rstrip()}")
...
00:     G1X66.43Y39.519E218.93118
01:     F600 E-1
02:     ;LAYER_COUNT:56
03:     ;LAYER:0
04:     M107
05:     G0 F2625 X36.605 Y37.768 Z0.425
06:     ;TYPE:SKIRT
07:     G1 F600 E0
08:     G1 F900 X37.439 Y37.1 E0.03559
09:     G1 X37.875 Y36.806 E0.05311
10:     G1 X39.165 Y36.079 E0.10243
11:     G1 X39.616 Y35.868 E0.11902
12:     G1 X40.498 Y35.536 E0.15041
13:     G1 X40.996 Y35.393 E0.16767
14:     G0 X64.468 Y39.131
15:     G0 X64.477 Y39.032
16:     ;TIME_ELAPSED:466.669759
17:     ;LAYER:1
18:     M140 S60
19:     M221 S100 T0
20:     M106 S68
21:     ;MESH:
22:     G0 F6562.5 X64.477 Y39.032 Z0.675
23:     ;TYPE:WALL-INNER
24:     G1 F600 E218.89162
25:     G1 F1800 X65.145 Y39.131 E218.90485
26:     G1 X65.806 Y39.296 E218.9182
27:     G1 X66.43 Y39.519 E218.93118

Ediit: Here's the doc for enumerate: https://docs.python.org/3/library/functions.html#enumerate

2

u/[deleted] Nov 09 '21

I appreciate the feedback I felt I was butchering the formatting. First time using Reddit for coding help.

1

u/CraigAT Nov 08 '21

How cool, I have not used a 3d printer before, so it's the first time I have come across this file format.

A quick Google suggests using G28 for moving the head away:
https://www.simplify3d.com/support/articles/3d-printing-gcode-tutorial/#G28

Is the "try / except" necessary? Would an "if / elif / else" do what you want?

Like u/Goobyalus pointed out, unless it has be the same file, then I would concur that going through the input line by line and outputting your edited lines to a new output file would be a good approach.

1

u/[deleted] Nov 09 '21

I'm using the "try/except" to compensate for the fact that when I separate the lines the lists are not all the same size. So when I try to find the Z variable in a line that isn't the same shape as my Z line I get a traceback. The "try/except" allows the program to ignore this expected error.

G28 is a specific command for the printer to home and zero it's axis' which you only want to happen during the beginning of the print. I just am needing the printer head to move out of the way of the print and dwell for 5 seconds.

1

u/CraigAT Nov 09 '21

Re: Try - I understand. As an alternative, when you have the line split into a list, you could use a "for" loop to cycle through the list items and "if' you find one item that starts with a Z then you could use that, otherwise do nothing.

Re: G28 - Okay! Out of curiosity what location are you defining as out of the way?

2

u/[deleted] Nov 11 '21

I am homing it to X1 Y290 Z(current height+10) then I'm telling the machine to pause there for 5 seconds.

2

u/[deleted] Nov 11 '21

That might work next time I'll think about incorporating it.