Created
December 21, 2013 14:44
-
-
Save vdudouyt/8070233 to your computer and use it in GitHub Desktop.
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
# Synopsis: | |
# LSUsbParser = create_parser('LSUsbResult', 'ID (\w+):(\w+) (.*)', | |
# LSUsbParser.parse(subprocess.check_output("lsusb")) | |
import functools, re, collections | |
def match_against_field_names(regex, field_names, string): | |
matched = re.search(regex, string) | |
if matched is not None: | |
return dict(zip(field_names, matched.groups())) | |
def create_parser(typename, regex, field_names): | |
matcher = functools.partial(match_against_field_names, regex, field_names) | |
NamedTupleClass = collections.namedtuple(typename, field_names) | |
NamedTupleClass.from_string = staticmethod(lambda s: | |
NamedTupleClass(**matcher(s)) if matcher(s) else None | |
) | |
NamedTupleClass.parse = staticmethod(lambda data: | |
map(NamedTupleClass.from_string, data.split("\n")) | |
) | |
return NamedTupleClass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment