-
-
Save SEVEZ/6ac65c3269d2de0242fd9b1ab4f6d25b to your computer and use it in GitHub Desktop.
Quick example of parsing an obj format (https://groups.google.com/d/topic/python_inside_maya/ISwX-LOAcnc/discussion)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Re: https://groups.google.com/d/topic/python_inside_maya/ISwX-LOAcnc/discussion | |
""" | |
class ObjProcessor(object): | |
def __init__(self, filename): | |
self.filename = filename | |
self._handlers = { | |
"v": self._handleVert, | |
"vn": self._handleNormal, | |
} | |
def process(self): | |
""" Process the file """ | |
with open(self.filename) as f: | |
if not self._validate(f): | |
raise IOError("Bad file format: %s" % self.filename) | |
handlers = self._handlers | |
for line in f: | |
# We don't want to handle blank lines or comments | |
line = line.strip() | |
if not line or line.startswith("#"): | |
continue | |
tokens = line.strip().split() | |
typ, args = tokens[0], tokens[1:] | |
# Look up a registered handler for this type of line | |
handler = handlers.get(typ) | |
if not handler: | |
print "No registered handler for line (skipping):", line | |
continue | |
# Delegate to our handler for the specific type | |
handler(args) | |
def _validate(self, fh): | |
""" | |
Accept an open file handle, and determine if it is | |
an expected format. Returns True if validaton passes. | |
Resets the file handle to the start when complete. | |
""" | |
fh.seek(0) | |
try: | |
for line in fh: | |
line = line.strip() | |
# Loop until we get a non blank/comment line | |
if not line or line.startswith('#'): | |
continue | |
# Does our real line start with our expected char? | |
return line.startswith('v') | |
finally: | |
fh.seek(0) | |
def _handleVert(self, args): | |
try: | |
x, y, z = args | |
except ValueError: | |
print "handleVert: Ignoring bad args:", args | |
return | |
print "handleVert:", (float(x), float(y), float(z)) | |
def _handleNormal(self, args): | |
try: | |
x, y, z = args | |
except ValueError: | |
print "handleNormal: Ignoring bad args:", args | |
return | |
print "handleNormal:", (float(x), float(y), float(z)) | |
if __name__ == "__main__": | |
import sys | |
obj = ObjProcessor(sys.argv[1]) | |
obj.process() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment