Created
June 14, 2013 07:32
-
-
Save gdugas/5780109 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
from django.core.management import BaseCommand, LaxOptionParser, CommandError, ManagementUtility | |
from django.core.management.base import handle_default_options | |
from optparse import make_option, OptionParser | |
import sys | |
class SubManagementUtil(ManagementUtility): | |
def __init__(self, argv=None, commands={}): | |
self.commands = commands | |
super(SubManagementUtil, self).__init__(argv) | |
def main_help_text(self, commands_only=False): | |
if commands_only: | |
usage = sorted(self.commands.keys()) | |
else: | |
usage = [ | |
"", | |
"Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name, | |
"", | |
"Available subcommands:", | |
] | |
for cmdname in self.commands.keys(): | |
usage.append(" %s" % cmdname) | |
return '\n'.join(usage) | |
def fetch_command(self, subcommand): | |
try: | |
cls = self.commands[subcommand] | |
return cls() | |
except KeyError: | |
sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" % \ | |
(subcommand, self.prog_name)) | |
sys.exit(1) | |
class SubCommand(BaseCommand): | |
args = "<subcommand>" | |
help = "Execute the specified subcommand" | |
subcommands = {} | |
def create_parser(self, prog_name, subcommand): | |
return LaxOptionParser(prog=prog_name, | |
usage=self.usage(subcommand), | |
version=self.get_version(), | |
option_list=self.option_list) | |
def print_help(self, prog_name, subcommand): | |
parser = self.create_parser(prog_name, subcommand) | |
parser.print_lax_help() | |
def get_subcommand(self, name): | |
if not name in self.subcommands: | |
raise CommandError('Unknown subcommand %s' % name) | |
else: | |
return self.subcommands[name]() | |
def run_from_argv(self, argv): | |
utility = SubManagementUtil(argv[1:], self.subcommands) | |
utility.execute() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment