def run(self, argv): commands_dir = os.path.dirname(__file__) parser = argparse.ArgumentParser(prog=sys.argv[0]) subparsers = parser.add_subparsers() # import all the modules in the command directory for module in os.listdir(commands_dir): if module == '__init__.py' or module[-3:] != '.py': continue command_mod = __import__('arm.commands.%s' % module[:-3], locals(), globals(), ['object'], -1) # add a subparser for each command ''' Assumes that each command defines a ``BaseCommand`` which inherits from ``arm.commands.Command`` ''' # search for all subclasses of ``arm.commands.Command`` for command_name, command_class in find_subclasses( command_mod, Command): # attch the command command_parser = subparsers.add_parser(command_name, help=command_class.help) # instantiate the command and provide its ``run`` method as the callback command = command_class(command_parser) command_parser.set_defaults(func=command.run) if getattr(argv, 'command', None): args = parser.parse_args([argv.command, '-h']) args = parser.parse_args(['-h'])
def run(self, argv): commands_dir = os.path.dirname(__file__) parser = argparse.ArgumentParser(prog=sys.argv[0]) subparsers = parser.add_subparsers() # import all the modules in the command directory for module in os.listdir(commands_dir): if module == '__init__.py' or module[-3:] != '.py': continue command_mod = __import__('arm.commands.%s' % module[:-3], locals(), globals(),['object'],-1) # add a subparser for each command ''' Assumes that each command defines a ``BaseCommand`` which inherits from ``arm.commands.Command`` ''' # search for all subclasses of ``arm.commands.Command`` for command_name, command_class in find_subclasses(command_mod, Command): # attch the command command_parser = subparsers.add_parser(command_name, help=command_class.help) # instantiate the command and provide its ``run`` method as the callback command = command_class(command_parser) command_parser.set_defaults(func=command.run) if getattr(argv, 'command',None): args = parser.parse_args([argv.command, '-h']) args = parser.parse_args(['-h'])
''' Find all the routes within this directory and import each. Assumes all commands are subclasses of ``arm.routes.Route`` and are called ``BaseCommand`` TODO: allow arbitrary name as long as it inherits from ``arm.routes.Route`` def find_subclasses(module, clazz): for name in dir(module): o = getattr(module, name) try: if (o != clazz) and issubclass(o, clazz): yield name, o except TypeError: pass ''' routes_dir = os.path.dirname(__file__) routes = [] for module in os.listdir(routes_dir): # skip this file and any other non-python file if module == '__init__.py' or module[-3:] != '.py': continue # import route module route_mod = __import__('arm.routes.%s' % module[:-3], locals(), globals(),['object'],-1) # search for all subclasses of ``arm.routes.Route`` for route_name,route_class in find_subclasses(route_mod, Route): # instantiate and append to ``routes`` list routes.append(route_class())