wolph / numpy-stl

Simple library to make working with STL files (and 3D objects in general) fast and easy.
http://numpy-stl.readthedocs.org/
BSD 3-Clause "New" or "Revised" License
605 stars 103 forks source link

open file from url #176

Closed caseywdunn closed 2 years ago

caseywdunn commented 2 years ago

I hope to use numpy-stl from within a google colab: https://colab.research.google.com/drive/1Z6RbnPAA5Gwd3XjH9KfPjdX9Dnrua1uh

I would like to load the file from a url: https://raw.githubusercontent.com/caseywdunn/python_graphics/main/ship.stl

I have tried a few different things, but I can't figure out how to get mesh.Mesh.from_file() to load from a url rather than a local file path. Is there an existing solution I missed? If not, this would be a great feature.

Thanks.

wolph commented 2 years ago

The trick is that mesh.Mesh.from_file() also has a fh (file handle) parameter.

We need to spool it into a BytesIO object Since a urllib.request file handle does not support seeking and such, after that it will work as expected:

import io
import urllib.request
from stl import mesh

URL  = 'https://raw.githubusercontent.com/caseywdunn/python_graphics/main/ship.stl'

with urllib.request.urlopen(URL) as response:
    fh = io.BytesIO(response.read())
    mesh.Mesh.from_file('some_stl_name_for_your_own_reference.stl', fh=fh)
caseywdunn commented 2 years ago

Beautiful - that worked like a charm. I was super impressed with numpy-stl, thanks for this great package.