python Code gibt Fehler aus

Python auf Einplatinencomputer wie Raspberry Pi, Banana Pi / Python für Micro-Controller
FrankWhite
User
Beiträge: 12
Registriert: Montag 26. März 2018, 19:33

Hallo,

ich bin neu hier und auch völlig neu in Pythin ergo habe keine Ahnung
Ich habe hier ein schönen code den ich gerne anwenden möchte der aber einen Fehler bringt
Habt ihr ne Ahnung was da nicht passt?

Code: Alles auswählen

# Simple GCode to Arduino hex format converter.

# It only understands G00 and G01 codes, nothing fancy!
#
# It will automatically scale the object to the full 12 bit
# range for my Arduino laser project, to change that
# you have to modify the scale in createObject().
#
# Typical files I worked with have been generated with
# http://ncplot.com/stickfont/stickfont.htm (StickFont 1.1)
#
# Usage: python convertGCode.py inputfile.nc outputfile.cpp

import math
import sys

def createObject(name, cmds):
  minx = miny = 10000000
  maxx = maxy = 0
  string = ""
  for cmd in cmds:
    if cmd[0] == 2:
      minx = min(minx,cmd[1])
      miny = min(miny,cmd[2])
      maxx = max(maxx,cmd[1])
      maxy = max(maxy,cmd[2])

  string += "const unsigned short draw_" + name + "[] PROGMEM = {\n";
  laserState = False
  
  biggestSide = max(maxx-minx, maxy-miny)
  # scale to the laser range
  scale = 4095. / biggestSide;
  print "bounding box x: ", minx, maxx
  print "bounding box y: ", miny, maxy
  print "scale: ", scale
  for cmd in cmds:
    if cmd[0] == 0:laserState = False
    if cmd[0] == 1:laserState = True
    if cmd[0] == 2:
      x = int(math.floor((cmd[1]-minx) * scale))
      y = int(math.floor((cmd[2]-miny) * scale))
      if laserState:
        x += 0x8000
      string += hex(x) + "," + hex(y) + ",\n"
  string += "};\n"
  return string

def run(input, output):
  result = ""
  f = open(input);
  lines = f.readlines()
  drawing = False
  posx = posy = 0.
    
  cmds = []
  for l in lines:
    if l.startswith("G00"):
      if drawing:
        cmds.append((0,))
      drawing = False
    elif l.startswith("G01"):
      drawing = True
      cmds.append((1,))
    elif l.startswith("X"):
      parts = l.split("Y")
      newposx = float(parts[0][1:])
      newposy = float(parts[1])
      cmds.append((2,newposx,newposy))
      posx = newposx
      posy = newposy

  result = createObject("object", cmds)
  
  o = open(output,"w")
  o.write(result)

if __name__ == "__main__":
  if len(sys.argv) < 3:
    print "Usage: convertGCode.py inputfile.nc outputfile.cpp"
  else:
    run(sys.argv[1], sys.argv[2])

Der Fehler ist folgender:
C:\Program Files\Python36>python convertGCode.py inputfile.nc outputfile.cpp
File "convertGCode.py", line 33
print "bounding box x: ", minx, maxx
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(t "bounding box x: ", minx, maxx)?


Grüße Frank der auf eure Hilfe hofft :)
Sirius3
User
Beiträge: 17711
Registriert: Sonntag 21. Oktober 2012, 17:20

Du versuchst Python2-Code mit Python3 auszuführen.
Sirius3
User
Beiträge: 17711
Registriert: Sonntag 21. Oktober 2012, 17:20

Außerdem ist der Code grottenschlecht:

Code: Alles auswählen

import math
import sys

def read_file(filename):
    drawing = False
    with open(filename) as lines:
        for line in lines:
            if lines.startswith("G00"):
                if drawing:
                    yield (0,)
                drawing = False
            elif lines.startswith("G01"):
                yield (1,)
                drawing = True
            elif lines.startswith("X"):
                parts = l.split("Y")
                newposx = float(parts[0][1:])
                newposy = float(parts[1])
                yield (2,newposx,newposy)

def get_bounds(cmds):
    x = [cmd[1] for cmd in cmds if cmd[0] == 2]
    y = [cmd[2] for cmd in cmds if cmd[0] == 2]
    return min(x), min(y), max(x), max(y)

def run(input, output):
    cmds = list(read_file(input))
    minx, miny, maxx, maxy = get_bounds(cmds)

    extent = max(maxx-minx, maxy-miny)
    # scale to the laser range
    scale = 4095. / extend
    print("bounding box x: ", minx, maxx)
    print("bounding box y: ", miny, maxy)
    print("scale: ", scale)

    result = []
    laser_state = False
    for cmd in cmds:
        if cmd[0] == 0:
            laser_state = False
        elif cmd[0] == 1:
            laser_state = True
        elif cmd[0] == 2:
            x = int(math.floor((cmd[1]-minx) * scale))
            y = int(math.floor((cmd[2]-miny) * scale))
            if laser_state:
                x += 0x8000
            result.append("0x{:04X},0x{:04X}".format(x, y))
    result = "const unsigned short draw_object[] PROGMEM = {{\n{}\n}};\n".format(
        ",\n".join(result)
    )
    with open(output, "w") as o:
        o.write(result)

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print "Usage: convertGCode.py inputfile.nc outputfile.cpp"
    else:
        run(sys.argv[1], sys.argv[2])
FrankWhite
User
Beiträge: 12
Registriert: Montag 26. März 2018, 19:33

Oh ^^ echt? Peinlich...woran erkennst du das ?
Heisst ich muss zuerst Python3 deinstallieren und Version 2 installieren? Oder kann man den Code hier in Version 2 umwanden?
Hast du zwecks Codeverbesserung irgendwelche Vorschläge?

Grüße Frank
__deets__
User
Beiträge: 14494
Registriert: Mittwoch 14. Oktober 2015, 14:29

Den verbesserten Code hat er doch gepostet. Und der sollte mit Python3 funktionieren.
FrankWhite
User
Beiträge: 12
Registriert: Montag 26. März 2018, 19:33

Hallo,

oh das hab ich jetzt übersehen, dachte das wäre meiner ^^
Ich habe das jetzt getestet > funktioniert nicht.

1.python 3.4.6 shell:
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> convertGCode.py
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
convertGCode.py
NameError: name 'convertGCode' is not defined
>>>
2. Windows cmd >
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> convertGCode.py
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
convertGCode.py
NameError: name 'convertGCode' is not defined
>>>
FrankWhite
User
Beiträge: 12
Registriert: Montag 26. März 2018, 19:33

und python 3.6 (64bit) cmd:
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> convertGCode2.py noobian.nc noobian.cpp
File "<stdin>", line 1
convertGCode2.py noobian.nc noobian.cpp
^
SyntaxError: invalid syntax
>>> convertGCode2.py
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'convertGCode2' is not defined
>>> convertGCode.py
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'convertGCode' is not defined
>>>
FrankWhite
User
Beiträge: 12
Registriert: Montag 26. März 2018, 19:33

ich weiß noch nicht mal welche von den 3 die richtige ist um das .py Program auszuführen..

Grüße Frank
Sirius3
User
Beiträge: 17711
Registriert: Sonntag 21. Oktober 2012, 17:20

Du versuchst bei allen drei Dein Pythonprogramm innerhalb der Python-Shell auszuführen. Pythonprogramme führt man von der Eingabeaufforderung aus aus:
[codebox=dos file=ba.bat]
C:\...> python3 convertGCode2.py noobian.nc noobian.cpp[/code]
FrankWhite
User
Beiträge: 12
Registriert: Montag 26. März 2018, 19:33

Hallo,
hier die Ausgabe: Es klappt nicht
Microsoft Windows [Version 10.0.16299.309]
(c) 2017 Microsoft Corporation. Alle Rechte vorbehalten.

C:\WINDOWS\system32>cd C:\Program Files\Python36

C:\Program Files\Python36>python3 convertGCode2.py noobian.nc noobian.cpp
Der Befehl "python3" ist entweder falsch geschrieben oder
konnte nicht gefunden werden.

C:\Program Files\Python36>python convertGCode2.py noobian.nc noobian.cpp
File "convertGCode2.py", line 58
print "Usage: convertGCode2.py inputfile.nc outputfile.cpp"
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(print "Usage: convertGCode2.py inputfile.nc outputfile.cpp")?

C:\Program Files\Python36>


Was ist da nicht richtig? Der meckert die Zeile :
File "convertGCode2.py", line 58
print "Usage: convertGCode2.py inputfile.nc outputfile.cpp" an

Grüße
Sirius3
User
Beiträge: 17711
Registriert: Sonntag 21. Oktober 2012, 17:20

Dann fehlen wohl in Zeile 58 die Klammern um `print`.
__deets__
User
Beiträge: 14494
Registriert: Mittwoch 14. Oktober 2015, 14:29

@FrankWhite: nimm einfach das original Programm & führ es mit Python 2.7 aus. Es mag nicht schön sein, tut aber seinen Job.
FrankWhite
User
Beiträge: 12
Registriert: Montag 26. März 2018, 19:33

Hi,
ich nerv schon wieder, nach dem ich die Klammern gesetzt habe wieder code fehler :(

C:\Program Files\Python36>convertGCode.py
Usage: convertGCode.py inputfile.nc outputfile.cpp

C:\Program Files\Python36>convertGCode.py noobian.nc noobian.cpp
Traceback (most recent call last):
File "C:\Program Files\Python36\convertGCode.py", line 60, in <module>
run(sys.argv[1], sys.argv[2])
File "C:\Program Files\Python36\convertGCode.py", line 27, in run
cmds = list(read_file(input))
File "C:\Program Files\Python36\convertGCode.py", line 8, in read_file
if lines.startswith("G00"):
AttributeError: '_io.TextIOWrapper' object has no attribute 'startswith'

C:\Program Files\Python36>

Grüße Frank
FrankWhite
User
Beiträge: 12
Registriert: Montag 26. März 2018, 19:33

@deets: ok muss ich vorher das 3.x deisnatllieren?

Grüße
Sirius3
User
Beiträge: 17711
Registriert: Sonntag 21. Oktober 2012, 17:20

@FrankWhite: die paar Tippfehler kannst Du selbst beheben:

Code: Alles auswählen

import sys
 
def read_file(filename):
    laser_state = False
    with open(filename) as lines:
        for line in lines:
            if line.startswith("G00"):
                laser_state = False
            elif line.startswith("G01"):
                laser_state = True
            elif line.startswith("X"):
                parts = line.split("Y")
                newposx = float(parts[0][1:])
                newposy = float(parts[1])
                yield laser_state, newposx, newposy
 
def get_bounds(cmds):
    x = [x for _, x, _ in cmds]
    y = [y for _, _, y in cmds]
    return min(x), min(y), max(x), max(y)
 
def run(input, output):
    cmds = list(read_file(input))
    minx, miny, maxx, maxy = get_bounds(cmds)
 
    extend = max(maxx-minx, maxy-miny)
    # scale to the laser range
    scale = 4095. / extend
    print("bounding box x: ", minx, maxx)
    print("bounding box y: ", miny, maxy)
    print("scale: ", scale)
 
    result = []
    for laser_state, x, y in cmds:
        x = int((x - minx) * scale)
        y = int((y - miny) * scale)
        if laser_state:
            x += 0x8000
        result.append("0x{:04X},0x{:04X}".format(x, y))
    result = "const unsigned short draw_object[] PROGMEM = {{\n  {}\n}};\n".format(
        ",\n  ".join(result)
    )
    with open(output, "w") as o:
        o.write(result)
 
if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: convertGCode.py inputfile.nc outputfile.cpp")
    else:
        run(sys.argv[1], sys.argv[2])
__deets__
User
Beiträge: 14494
Registriert: Mittwoch 14. Oktober 2015, 14:29

FrankWhite hat geschrieben:@deets: ok muss ich vorher das 3.x deisnatllieren?

Grüße
Nein. Die installieren sich problemlos parallel. Musst nur beim ausführen aufpassen das richtige zu nehmen. Am besten durch den vollen Pfad.
FrankWhite
User
Beiträge: 12
Registriert: Montag 26. März 2018, 19:33

@Sirius: tut mir leid ich habe keine Ahnung, deshalb kann ich es leider nicht.
Der letzte Code bringt leider auch wieder Fehler :(
>convertGCode.py noobian.nc noobian.cpp
Traceback (most recent call last):
File "C:\Program Files\Python36\convertGCode.py", line 50, in <module>
run(sys.argv[1], sys.argv[2])
File "C:\Program Files\Python36\convertGCode.py", line 23, in run
cmds = list(read_file(input))
File "C:\Program Files\Python36\convertGCode.py", line 5, in read_file
with open(filename) as lines:
FileNotFoundError: [Errno 2] No such file or directory: 'noobian.nc'

ich glaube ich nehm das 2.x

Grüße
Frank
Sirius3
User
Beiträge: 17711
Registriert: Sonntag 21. Oktober 2012, 17:20

@FrankWhite: ich kann bei Dir auch keine Anzeichen dafür erkennen, dass Du daran etwas ändern willst. Auch Python2 wird die Datei, die offensichtlich nicht dort existiert, wo Du denkst, finden.
FrankWhite
User
Beiträge: 12
Registriert: Montag 26. März 2018, 19:33

Hallo,

das ist nicht zu glauben ich habe 3.6 deinstalliert und 2.7 installiert, Rechner neustart
Programm ausführen wollen:

C:\Python27>python convertGCode.py noobian.nc noobian.cpp
Traceback (most recent call last):
File "convertGCode.py", line 81, in <module>
run(sys.argv[1], sys.argv[2])
File "convertGCode.py", line 66, in run
newposx = float(parts[0][1:])
ValueError: invalid literal for float(): -0,31

warum, hiiiilfee

Grüße Frank
FrankWhite
User
Beiträge: 12
Registriert: Montag 26. März 2018, 19:33

@Sirius3: warum unterstellst du mir sowas?
Ich habe alle 3 Dateien in das Python Verzeichnis kopiert aölso glaube ich das das so richtig ist

Grüße Frank
Antworten