Python Forum

Full Version: Help moding python script to edit Gcode
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Hi there!
I'm new to python, haven't done any coding in 20 years. I used to do Basic code for the Basic stamp controller.
Anyways, I have a script that a nice person made for me that will strip the comment lines out of my Gcode. The software I use to create the Gcode is LightBurn.
LightBurn software adds a ; to the beginning of every comment line. My CNC controller does not understand ; and goes nuts!!! But I would rather keep the comment lines instead of stripping it out. To do this I would need to add a( at the start of the comment line and ) at the end. So basically I'd like Python to find any line that starts with ; and then add ( ) to that whole line. I googled to try to learn this myself but couldn't come up with info geared to what I'm after.
Here is the script and some sample code. Any help would be great!


import sys
import os

if len(sys.argv) != 2:
print('Usage: python nocomment.py <file.gcode>')
sys.exit(1)

in_file = os.path.abspath(sys.argv[1])

if not os.path.isfile(in_file):
print(in_file + ' does not exist!')
sys.exit(1)

with open(in_file, 'r+') as f:
out_lines = []
for line in f.readlines():
if not line.lstrip().startswith(';'):
out_lines.append(line)

if(len(out_lines) > 0):
f.seek(0)
f.truncate()
f.writelines(out_lines)

print('comment removal complete for ' + in_file)


And the sample Gcode:

; LightBurn 0.9.20
; GRBL-M3 (1.1e or earlier) device profile, user origin
; Bounds: X103.74 Y238.22 to X190.39 Y319.63

;USER START SCRIPT



;USER START SCRIPT

G00 G17 G40 G21 G54
G90
G0 X0 Y0
G91
; Scan+Cut @ 1200 mm/min, 100% power
M9
M5
G0X16.15Y6.26
; Layer C01
M3
G1X0.39F1200S255
G1X72.62Y0.2F2800S0
G1X-0.69F1200S255
G1X-3.3F2800S0
G1X-2.8F1200S255
G1X-0.7S0
G1X-3.5S255

Thanks
Glen
Please use the bbcode "python" tags for your code.

Looks like the meat is here:
if not line.lstrip().startswith(';'):
    out_lines.append(line)
If it's not commented, add it to out_lines. You just need to do something else when it is a comment. Perhaps something like:

if line.lstrip().startswith(';'):
    out.lines.append("(" + line + ")")
else:
    out_lines.append(line)
Hi,
Thanks for the help!
I gave it a try and this is the message I'm getting in the command prompt window.
I tried moving the Else around on the line a bit but didn't help.

Microsoft Windows [Version 10.0.17134.1]
© 2018 Microsoft Corporation. All rights reserved.

C:\Users\Glen>d:

D:\>cd lightburn

D:\lightburn>comment.py test.gc
File "D:\lightburn\comment.py", line 19
else:
^
SyntaxError: invalid syntax

D:\lightburn>

Edit got the else figured out but now have this issue.

D:\lightburn>comment.py test.gc
Traceback (most recent call last):
File "D:\lightburn\comment.py", line 18, in <module>
out.lines.append("(" + line + ")")
NameError: name 'out' is not defined

D:\lightburn>


Thanks
Glen
import sys
import os

if len(sys.argv) != 2:
    print('Usage: python nocomment.py <file.gcode>')
    sys.exit(1)
    
in_file = os.path.abspath(sys.argv[1])

if not os.path.isfile(in_file):
    print(in_file + ' does not exist!')
    sys.exit(1)

with open(in_file, 'r+') as f:
    out_lines = []
    for line in f.readlines():
       if line.lstrip().startswith(';'):
        out.lines.append("(" + line + ")")
       else:
        out_lines.append(line)
            
    if(len(out_lines) > 0):
        f.seek(0)
        f.truncate()
        f.writelines(out_lines)
        
print('comment line complete for ' + in_file)
Ok getting closer edited it to get ride of the . and changed it to _ HERE---- out.lines ------
but now it looks like this.

(; LightBurn 0.9.20
)(; GRBL-M3 (1.1e or earlier) device profile, user origin
)(; Bounds: X103.74 Y238.22 to X190.39 Y319.63
)
(;USER START SCRIPT
) 


(;USER START SCRIPT
)
G00 G17 G40 G21 G54
G90
G0 X0 Y0
G91
(; Scan+Cut @ 1200 mm/min, 100% power
)M9
M5
G0X16.15Y6.26
(; Layer C01
)M3
Glen
Some fix done,try this.
import sys
import os

if len(sys.argv) != 2:
    print('Usage: python nocomment.py <file.gcode>')
    sys.exit(1)
in_file = os.path.abspath(sys.argv[1])

if not os.path.isfile(in_file):
    print(f'{in_file} does not exist!')
    sys.exit(1)

with open(in_file, 'r+') as f:
    out_lines = []
    for line in f:
        line = line.strip()
        if line.startswith(';'):
            out_lines.append(f'({line})')
        else:
            out_lines.append(line)

    if len(out_lines) > 0:
        f.seek(0)
        f.truncate()
        f.write('\n'.join(out_lines))

print(f'comment removal complete for {in_file}')
(Jan-03-2021, 03:06 AM)snippsat Wrote: [ -> ]Some fix done,try this.
import sys
import os

if len(sys.argv) != 2:
    print('Usage: python nocomment.py <file.gcode>')
    sys.exit(1)
in_file = os.path.abspath(sys.argv[1])

if not os.path.isfile(in_file):
    print(f'{in_file} does not exist!')
    sys.exit(1)

with open(in_file, 'r+') as f:
    out_lines = []
    for line in f:
        line = line.strip()
        if line.startswith(';'):
            out_lines.append(f'({line})')
        else:
            out_lines.append(line)

    if len(out_lines) > 0:
        f.seek(0)
        f.truncate()
        f.write('\n'.join(out_lines))

print(f'comment removal complete for {in_file}')

Thanks snippsat,
That worked!!!HAHA bonus!!!!
So why did that other bit of code not work properly and put the )on the next line?


Glen
(Jan-03-2021, 03:20 AM)AntaresSky Wrote: [ -> ]So why did that other bit of code not work properly and put the )on the next line?
There was \n(new line) that should not be there for this task.
When use f.readlines() it add a \n automatically.
So what i did was to remove all new \n(line 16),then do the task.
Then last add \n with '\n'.join(out_lines) as writelines() does not add newline characters on its own.

A tips use repr() to see all👀
So you add it where you want to take a look.
with open(in_file, 'r+') as f:
    out_lines = []
    for line in f.readlines():
        print(repr(line))
with open(in_file, 'r+') as f:
    out_lines = []
    for line in f:
        line = line.strip()
        print(repr(line))
(Jan-03-2021, 11:54 AM)snippsat Wrote: [ -> ]When use f.readlines() it add a \n automatically.
Just a small note, that it's not readlines() that add \n. Newline ending is there in the file. And thus also present when just iterate over file-handle f and @snippsat removes it with strip().
Interesting!
So the line in the original script L.Lstrip is different then your script Line.strip?

I take it the Line.Lstrip is telling it to removed the whole line?
But I'm still not totally clear on what the Line.strip does. Can you dumb it down a bit for me?
ORIGINAL SCRIPT:
with open(in_file, 'r+') as f:
    out_lines = []
    for line in f.readlines():
        if not line.lstrip().startswith(';'):
            out_lines.append(line)
            
    if(len(out_lines) > 0):
        f.seek(0)
        f.truncate()
        f.writelines(out_lines)
YOUR NEW AND IMPROVED SCRIPT:

with open(in_file, 'r+') as f:
    out_lines = []
    for line in f:
        line = line.strip()
        if line.startswith(';'):
            out_lines.append(f'({line})')
        else:
            out_lines.append(line)
 
    if len(out_lines) > 0:
        f.seek(0)
        f.truncate()
        f.write('\n'.join(out_lines))
 
print(f'comment fix complete for {in_file}')
Glen
Pages: 1 2