Off topic coding help required
-
This is only very loosely related to 3D printing and Duet, hence posted in the "Off Topic" section.
Having shared my UV motion planning Python script with others, a bug has raised it's ugly head and I could use some help in finding an elegant way of dealing with it.
In a nutshell, I need to ascertain the (numeric) X and Y values from a line of gcode for example G1 X285.006 Y75.751 E14.29272.
Not being a writer of code, the approach I've taken is to search that string, see where "X" appears in it, then read the next 7 characters into a temporary string and then convert it to a float. This is all fine and Dandy BUT......What I've missed is that the value for X isn't necessarily 3 digits followed by a dot and then 3 more digits. It might only be 2 digits followed by a dot and 3 digits. Actually, that still works because the last character of the 7 character string is a space. But any value <10 will fail because the resultant string with have "Y" as it's last character and so it can't be converted to a float.
So I guess what I need is an elegant way to read a variable length number from within a longer string. I suppose I could do it by reading each character after the "X" and checking if it's a digit or dot, if so add it to the temp string and check the next character, if not (or if it's a space) break then convert the resultant string into a float. That all seems a bit complex and I can't help thinking there must be an easier or more elegant way. I can't help thinking that RepRap firmware must do this although maybe it uses some sort of command that cannot be replicated in Python.
Anyway, all donations, help or ideas will be gratefully received.
-
This post is deleted! -
you want to find "X" and then read until the next character that is neither a number nor a dot. Python provides a facility for matching of regular occurrences of strings called "regular expressions".
To match anything that's a number, possibly with a . mixed in, a possible regular expression for that is
[0-9.]
You can try regular expressions interactively on websites like https://regexr.com/
The Pytho documentation about regular expressions is at https://docs.python.org/3/library/re.html
I hope this helps.
-
@deckingman Hi Ian. You can find a code example of how to read X and Y coords of GCode using Python here:
https://github.com/CNCKitchen/GradientInfill/blob/eee6aa14be3aa886f75c19ee52442e85748ffa65/GradientInfill.py#L113 -
-
Update - that looks like it's done the trick - thanks again guys.