-
Notifications
You must be signed in to change notification settings - Fork 5
/
OptionHandler.py
63 lines (47 loc) · 1.62 KB
/
OptionHandler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python
"""
Thomas Klijnsma
"""
########################################
# Imports
########################################
import os
import importlib
import argparse
########################################
# Main
########################################
def flag_as_option(function):
function.is_option = True
return function
def flag_as_parser_options(function):
function.is_parser_options = True
return function
class OptionHandler(object):
"""docstring for OptionHandler"""
registered_functions = {}
def __init__(self, modules=[]):
self.parser = argparse.ArgumentParser()
self.process_modules(modules)
def set_parser(self, parser):
self.parser = parser
def process_modules(self, modules):
for module in modules:
self.process_module(module)
def process_module(self, module):
mod = importlib.import_module(module)
for attr in dir(mod):
if hasattr( getattr(mod, attr), 'is_option' ):
self.make_option( getattr(mod, attr) )
elif hasattr( getattr(mod, attr), 'is_parser_options' ):
getattr(mod, attr)(self.parser)
def make_option(self, function):
self.parser.add_argument('--{0}'.format(function.__name__), action='store_true')
self.registered_functions[function.__name__] = function
return function
def parse(self):
self.args = self.parser.parse_args()
def execute_functions(self):
for name, function in self.registered_functions.iteritems():
if getattr(self.args, name):
function(self.args)