import logging import sys import optparse import wizard class Error(wizard.Error): """Base error class for all command errors""" pass def makeLogger(options): logger = logging.getLogger("main") logger.setLevel(logging.INFO) stdout = logging.StreamHandler(sys.stdout) stdout.setFormatter(logging.Formatter(" " * int(options.indent) + '%(message)s')) logger.addHandler(stdout) if options.log_file: file = logging.FileHandler(options.log_file) logger.addHandler(file) if options.debug: logger.setLevel(logging.DEBUG) else: stdout.setLevel(logging.WARNING) if options.verbose or options.dry_run: stdout.setLevel(logging.INFO) if options.log_file: file.setLevel(logging.INFO) return logger def makeBaseArgs(options, **grab): """Takes parsed options, and breaks them back into a command line string that we can pass into a subcommand""" args = [] grab["log_file"] = "--log-file" grab["debug"] = "--debug" grab["verbose"] = "--verbose" grab["indent"] = "--indent" #grab["log_db"] = "--log-db" for k,flag in grab.items(): value = getattr(options, k) if not value and k != "indent": continue args.append(flag) if type(value) is not bool: if k == "indent": value += 4 args.append(str(value)) return args class NullLogHandler(logging.Handler): """Log handler that doesn't do anything""" def emit(self, record): pass class WizardOptionParser(optparse.OptionParser): """Configures some default user-level options""" def __init__(self, *args, **kwargs): optparse.OptionParser.__init__(self, *args, **kwargs) self.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help="Turns on verbose output") self.add_option("--debug", dest="debug", action="store_true", default=False, help="Turns on debugging output") self.add_option("--log-file", dest="log_file", default=None, help="Logs verbose output to file") self.add_option("--indent", dest="indent", default=0, help="Indents stdout, useful for nested calls") def parse_all(self, argv, logger): options, numeric_args = self.parse_args(argv) return options, numeric_args, logger and logger or makeLogger(options)