jminardi / mecode

GCode for all
MIT License
221 stars 61 forks source link

Outfile fails on file-like objects #64

Closed fake-name closed 6 years ago

fake-name commented 6 years ago

    sbuf = StringIO.StringIO()
    with mecode.G(outfile=sbuf, print_lines=False) as g:
        pass

This fails:

Traceback (most recent call last):
  File "scan_gcode_gen.py", line 154, in <module>
    scan_generate(**pla)
  File "scan_gcode_gen.py", line 112, in scan_generate
    return generate_plane(**kwargs)
  File "scan_gcode_gen.py", line 41, in generate_plane
    with mecode.G(outfile=sbuf, print_lines=False) as g:
  File "/usr/local/lib/python2.7/dist-packages/mecode/main.py", line 202, in __init__
    self.setup()
  File "/usr/local/lib/python2.7/dist-packages/mecode/main.py", line 298, in setup
    self._write_header()
  File "/usr/local/lib/python2.7/dist-packages/mecode/main.py", line 927, in _write_header
    self._write_out(lines=fd.readlines())
  File "/usr/local/lib/python2.7/dist-packages/mecode/main.py", line 906, in _write_out
    self._write_out(line)
  File "/usr/local/lib/python2.7/dist-packages/mecode/main.py", line 909, in _write_out
    if 'b' in self.out_fd.mode:  # encode the string to binary if needed
AttributeError: StringIO instance has no attribute 'mode'

Basically, the mode attribute is not a part of the required interface for file-like objects, and you can't rely on it being present.

The proper solution here is obviously to switch to python 3, because it explicitly fixes issues like this.

For the moment, just probing with hasattr() should be a decent work-around.