44for custom structures
55"""
66
7+ import os
8+ import importlib
9+
710from lxml import objectify
811
912
@@ -123,15 +126,19 @@ def __init__(self, name):
123126
124127
125128class StructGenerator (object ):
126- def __init__ (self , path , output ):
127- self .path = path
128- self .output = output
129+ def __init__ (self ):
129130 self .model = []
130- self ._file = None
131131
132- def _make_model (self ):
133- obj = objectify .parse (self .path )
132+ def make_model_from_string (self , xml ):
133+ obj = objectify .fromstring (xml )
134+ self ._make_model (obj )
135+
136+ def make_model_from_file (self , path ):
137+ obj = objectify .parse (path )
134138 root = obj .getroot ()
139+ self ._make_model (root )
140+
141+ def _make_model (self , root ):
135142 for child in root .iter ("{*}StructuredType" ):
136143 struct = Struct (child .get ("Name" ))
137144 array = False
@@ -152,23 +159,29 @@ def _make_model(self):
152159 struct .fields .append (field )
153160 self .model .append (struct )
154161
155- def run (self ):
156- self ._make_model ()
157- self ._file = open (self .output , "wt" )
158- self ._make_header ()
162+ def save_to_file (self , path ):
163+ _file = open (path , "wt" )
164+ self ._make_header (_file )
159165 for struct in self .model :
160- self ._file .write (struct .get_code ())
161- self ._file .close ()
166+ _file .write (struct .get_code ())
167+ _file .close ()
168+
169+ def save_and_import (self , path ):
170+ self .save_to_file (path )
171+ name = os .path .basename (path )
172+ name = os .path .splitext (name )[0 ]
173+ mymodule = importlib .import_module (name )
174+ mydict = {struct .name : getattr (mymodule , struct .name ) for struct in self .model }
175+ return mydict
162176
163177 def get_structures (self ):
164- self ._make_model ()
165178 ld = {}
166179 for struct in self .model :
167180 exec (struct .get_code (), ld )
168181 return ld
169182
170- def _make_header (self ):
171- self . _file .write ("""
183+ def _make_header (self , _file ):
184+ _file .write ("""
172185'''
173186THIS FILE IS AUTOGENERATED, DO NOT EDIT!!!
174187'''
0 commit comments