def main(): options = [ Option('-d', '--dontcares', dest='dc', default='', help='comma-separated don\'t-cares', metavar='D'), Option('-o', '--ones', dest='ones', default='', help='comma-separated ones', metavar='O'), Option('-z', '--zeros', dest='zeros', default='', help='comma-separated zeros', metavar='Z') ] f = IndentedHelpFormatter() def raw_format(s): return s + '\n' f.format_description = raw_format optparser = OptionParser(description=__doc__, formatter=f) optparser.add_options(options) opts, args = optparser.parse_args() if len(sys.argv) == 1 or args: optparser.print_help() exit() opts.dc = [int(i) for i in opts.dc.split(',') if i] opts.ones = [int(i) for i in opts.ones.split(',') if i] opts.zeros = [int(i) for i in opts.zeros.split(',') if i] soln = qm(dc=opts.dc, ones=opts.ones, zeros=opts.zeros) if len(soln) == 0: sys.stdout.write('contradiction\n') elif len(soln) == 1 and soln[0].count('X') == len(soln[0]): sys.stdout.write('tautology\n') else: sys.stdout.write(' '.join(soln) + '\n')
def __init__(self, indent_increment=2, max_help_position=32, width=78, short_first=1): IndentedHelpFormatter.__init__(self, indent_increment, max_help_position, width, short_first)
def __init__(self, max_help_position=30, useColors=True, usageColor="\033[1;34m", headingColor="\033[1;33m", descriptionColor="\033[1;31m", optionsColor="\033[1;32m", epilogColor="\033[1;31m",): """ Constructor of the DwfHelpFormatter class. @param self : the object pointer. @param max_help_position : starting column of the help text. Default is 30. @param useColors : enable or disable the use of color formats. Default is True. @param usageColor : color of the command usage text. @param headingColor : color of the group heading text. @param descriptionColor : color of the command description text. @param optionsColor : color of the options. @param epilogColor : color of the help epilog text. Constructor of the DwfHelpFormatter class used to set formatting of help text and enable or disable this formatting. """ IndentedHelpFormatter.__init__(self, indent_increment=0, max_help_position=max_help_position, width=None, short_first=True) self._isLinuxKSL = False # Know if linux konsole self._useColors = useColors # Use console color str if available self._usageColor = usageColor self._descriptionColor = descriptionColor self._headingColor = headingColor self._optionsColor = optionsColor self._epilogColor = epilogColor self._noColor = "\033[0m" self.option_raw_strings = {} self._short_opt_fmt = "%s [%s]" self._long_opt_fmt = "%s=[%s]"
def __init__ (self, indent_increment=2, max_help_position=32, width=78, short_first=1): IndentedHelpFormatter.__init__( self, indent_increment, max_help_position, width, short_first)
def __init__(self, *args, **kwargs): from textwrap import fill, wrap IndentedHelpFormatter.__init__(self, *args, **kwargs) tw = type('textwrap_mock', (object, ), dict( fill=staticmethod(fill), wrap=staticmethod(lambda *args, **kwargs: wrap(*args, **dict(kwargs, break_on_hyphens=False)), ))) self.format_option.func_globals['textwrap'] = tw
def __init__(self, *args, **kwargs): from textwrap import fill, wrap IndentedHelpFormatter.__init__(self, *args, **kwargs) tw = type('textwrap_mock', (object, ), dict( fill=staticmethod(fill), wrap=staticmethod(lambda *args, **kwargs: wrap(*args, **dict(kwargs, break_on_hyphens=False)), ))) self.format_option.__globals__['textwrap'] = tw
def __init__(self, indent_increment=0, max_help_position=80, width=None, short_first=1): IndentedHelpFormatter.__init__(self, indent_increment=indent_increment, max_help_position=max_help_position, width=width, short_first=short_first)
def getArguments(): ''' Gets command-line arguments and handles validation ''' parser = OptionParser("%prog [options] file", formatter=IndentedHelpFormatter(4, 80, 130)) parser.add_option("-n", "--num-records", dest="numrecords", help="Number of records per table.", default=1000000) parser.add_option("-c", "--cadence", dest="cadence", help="Record cadence in seconds.", default=10) parser.add_option("-d", "--database-name", dest="dbname", help="Database name.", default="helioviewer") parser.add_option( "-t", "--table-name", dest="tablename", help= "Table name (If multiple tables are requested, a number will be affixed to each table).", default="images") parser.add_option( "-i", "--insert-size", dest="insertsize", help="How many records should be included in each INSERT statement", default=10) parser.add_option("-u", "--num-tables", dest="numtables", help="The number of tables to create.", default=1) parser.add_option( "", "--postgres", dest="postgres", help= "Whether output should be formatted for use by a PostgreSQL database.", action="store_true") try: options, args = parser.parse_args() except: sys.exit(2) # check for filename if len(args) != 1: usage(parser) print "Error: Output file not specified" sys.exit(2) else: options.filename = args[0] return options
def format_epilog(self, epilog): buf = StringIO() buf.write(IndentedHelpFormatter.format_epilog(self, epilog)) buf.write("\n") buf.write(self._wrap_it("For further information check out: " "http://anvil.readthedocs.org")) buf.write("\n") return buf.getvalue()
def parse_options(): """ Parse command line options """ import version formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [options]", version='%prog ' + str(version.version)) parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0] parser.description = "Convert station list (TV_CHANNELS) from local_conf.py for tvtime" parser.add_option( '--band', choices=bands, default=bands[0], metavar='BAND', help='Select the TV band [default:%default], choose from: "' + '", "'.join(bands) + '"') opts, args = parser.parse_args() return opts, args
def parse_options(): """ Parse command line options """ import version formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=36, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage=""" Freevo helper script to start Freevo on lirc command. Everytime Freevo is not running and EXIT or POWER is pressed, this script will start Freevo. If the display in freevo.conf is x11 or dga, this script will start Freevo in a new X session.""", version='%prog ' + version.version) parser.add_option('--start', action='store_true', default=False, help='start the daemon [default:%default]') parser.add_option('--stop', action='store_true', default=False, help='stop the daemon [default:%default]') return parser.parse_args()
def getArguments(): ''' Gets command-line arguments and handles validation ''' parser = OptionParser("%prog [options] file", formatter=IndentedHelpFormatter(4,80)) parser.add_option("-d", "--database-name", dest="dbname", help="Database name.", default="helioviewer", metavar="DB_Name") parser.add_option("-u", "--database-user", dest="dbuser", help="Database username.", default="helioviewer", metavar="Username") parser.add_option("-p", "--database-pw", dest="dbpass", help="Database password.", default="helioviewer", metavar="Password") parser.add_option("-t", "--table-name", dest="tablename", help="Table name.", default="image", metavar="Table_Name") parser.add_option("-n", "--num-queries", dest="numqueries", help="Number of queries to simulate.", default=100) parser.add_option("-m", "--num-threads", dest="numthreads", help="Number of simultaneous threads to execute", default = 1) parser.add_option("-c", "--count", dest="count", help="Number of rows in the database (queried with COUNT if not specified, which is slow on many transaction safe databases, e.g. postgres)") parser.add_option("", "--timing-method", dest="timingmethod", help="Timing method, possible options are timeit and now", default="timeit") parser.add_option("", "--multiple-connections", dest="multipleconnections", help="Use one connection per query", action="store_true") parser.add_option("", "--postgres", dest="postgres", help="Whether output should be formatted for use by a PostgreSQL database.", action="store_true") try: options, args = parser.parse_args() except: sys.exit(2) # check for filename if len(args) != 1: usage(parser) print "Error: Output file not specified" sys.exit(2) else: options.filename = args[0] return options
def main(): global conf command_container = BeakerCommandContainer(conf=conf) formatter = IndentedHelpFormatter(max_help_position=60, width=120) parser = BeakerOptionParser(version=__version__, conflict_handler='resolve', command_container=command_container, default_command="help", formatter=formatter) # Need to deal with the possibility that requests is not importable... try: import requests maybe_http_error = (requests.HTTPError, ) except ImportError: maybe_http_error = () # This is parser.run(), but with more sensible error handling cmd, cmd_opts, cmd_args = parser.parse_args() try: return cmd.run(*cmd_args, **cmd_opts.__dict__) except krbV.Krb5Error, e: if e.args[0] == krbV.KRB5KRB_AP_ERR_TKT_EXPIRED: sys.stderr.write( 'Kerberos ticket expired (run kinit to obtain a new ticket)\n') return 1 elif e.args[0] == krbV.KRB5_FCC_NOFILE: sys.stderr.write( 'No Kerberos credential cache found (run kinit to create one)\n' ) return 1 else: raise
def parse_options(): """ Parse command line options """ import version formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [options]", version='%prog ' + str(version.version)) prog = os.path.basename(sys.argv[0]) parser.prog = os.path.splitext(prog)[0] parser.description = "Downloads the listing for xmltv and cache the data" parser.add_option( '-u', '--update', action='store_true', default=False, help= 'Update the database only, do not attempt to retrieve listings. [default:%default]' ) opts, args = parser.parse_args() return opts, args
def get_options(): '''Gets command-line parameters''' parser = OptionParser('%prog [options]', formatter=IndentedHelpFormatter(4,100)) params = [ ('-d', '--database-name', 'dbname', 'Database to insert images into'), ('-u', '--database-user', 'dbuser', 'Helioviewer.org database user'), ('-p', '--database-pass', 'dbpass', 'Helioviewer.org database password'), ('-i', '--input-dir', 'source', 'Directory containing files to process'), ('-o', '--output-dir', 'destination', 'Directory to move files to') ] for param in params: parser.add_option(param[0], param[1], dest=param[2], help=param[3]) try: options, args = parser.parse_args() for param in params: if getattr(options, param[2]) is None: raise Exception("ERROR: missing required parameter %s.\n" % param[2]) except Exception, e: print_help(parser) print e sys.exit(2)
def parse_options(): """ Parse command line options """ import version tmp = os.environ.has_key('TEMP') and os.environ['TEMP'] or '/tmp' formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [options]", version='%prog ' + str(version.version)) parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0] parser.description = "Helper to convert a favorites.txt to a favorites.pickle" parser.add_option('-v', '--verbose', action='count', default=0, help='set the level of verbosity [default:%default]') parser.add_option('--favorites-txt', metavar='FILE', default=config.TV_RECORD_FAVORITES_LIST, help='the favorites.txt file to read and process [default:%default]') parser.add_option('--favorites-pickle-out', metavar='FILE', default=os.path.join(tmp, 'favorites.pickle'), help='the reritten favorites.pickle file [default:%default]') parser.add_option('--favorites-txt-out', metavar='FILE', default=os.path.join(tmp, 'favorites.txt'), help='the reritten favorites.txt file [default:%default]') parser.add_option('--schedule-pickle-out', metavar='FILE', default=os.path.join(tmp, 'schedule.pickle'), help='the reritten schedule.pickle file [default:%default]') opts, args = parser.parse_args() return opts, args
def _format_text(self, text): paragraphs = re.split('\n([ \t]*\n)+', text) paragraphs = [ IndentedHelpFormatter._format_text(self, p.strip()) for p in paragraphs ] return '\n'.join(paragraphs) # each already ends in a newline
def main(): p = OptionParser( "%prog SERVER:/PATH [options] flags|testcodes\n" " %prog --help\n" " %prog SHOWOPTION", version="%prog " + VERSION, formatter=IndentedHelpFormatter(2, 25)) opt, args = scan_options(p) nfs4lib.SHOW_TRAFFIC = opt.showtraffic # Create test database tests, fdict, cdict = testmod.createtests('servertests') # Deal with any informational options if opt.showflags: printflags(fdict.keys()) sys.exit(0) if opt.showcodes: codes = cdict.keys() codes.sort() for c in codes: print c sys.exit(0) # Grab server info and set defaults if not args: p.error("Need a server") url = args.pop(0) opt.server, opt.port, opt.path = parse_url(url) if not opt.server: p.error("%s not a valid server name" % url) if not opt.port: opt.port = 2049 else: opt.port = int(opt.port) if not opt.path: opt.path = [] else: opt.path = unixpath2comps(opt.path) # Check --use* options are valid for attr in dir(opt): if attr.startswith('use') and attr != "usefh": path = getattr(opt, attr) #print attr, path if path is None: path = opt.path + ['tree', attr[3:]] else: # FIXME - have funct that checks path validity if path[0] != '/': p.error("Need to use absolute path for --%s" % attr) # print path if path[-1] == '/' and attr != 'usedir': p.error("Can't use dir for --%s" % attr) try: path = unixpath2comps(path) except Exception, e: p.error(e) setattr(opt, attr, [comp for comp in path if comp])
def _format_text(self, text): __doc__ = IndentedHelpFormatter._format_text return "\n\n".join( t if len(t) == 0 or t[0].isspace() else IndentedHelpFormatter._format_text(self, t) for t in text.split("\n\n") )
def __init__(self, prog=None, usage=None): formatter = IndentedHelpFormatter( indent_increment=2, max_help_position=80, width=100, short_first=1) optparse.OptionParser.__init__(self, prog=prog, usage=usage, formatter=formatter)
def standalone_help(self): help_text = self.name_with_arguments().ljust( len(self.name_with_arguments()) + 3) + self.help_text + "\n\n" if self.long_help: help_text += "%s\n\n" % self.long_help help_text += self.option_parser.format_option_help( IndentedHelpFormatter()) return help_text
def MyOptionParser(prog, usage): formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=80, width=100, short_first=1) parser = LenientOptionParser(prog=prog, formatter=formatter, usage=usage) parser.disable_interspersed_args() return parser
def parse_options(): """ Parse command line options """ import version thumbsize = config.WWW_IMAGE_THUMBNAIL_SIZE imagesize = config.WWW_IMAGE_SIZE formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=36, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage=""" Make image MRSS feed for CoolIris (http://www.cooliris.com/site/support/download-all-products.php) Usage: %prog [options]""", version='%prog ' + version.version) parser.add_option('-v', '--verbose', action='count', default=0, help='set the level of verbosity') parser.add_option( '-r', '--rebuild', action='store_true', dest='force', default=False, help='rebuild the thumbnails and images [default:%default]') parser.add_option('-t', '--thumb-size', action='store', dest='thumbsize', default=thumbsize, metavar='SIZE', help='size of thumbnail images [default:%default]') parser.add_option('-i', '--image-size', action='store', dest='imagesize', default=imagesize, metavar='SIZE', help='size of images [default:%default]') parser.add_option('-T', '--no-thumbs', action='store_true', dest='nothumbs', default=False, help='do not build thumbnail images [default:%default]') parser.add_option('-I', '--no-images', action='store_true', dest='noimages', default=False, help='Do not build images [default:%default]') return parser.parse_args()
def format_epilog(self, epilog): buf = StringIO() buf.write(IndentedHelpFormatter.format_epilog(self, epilog)) buf.write("\n") buf.write( self._wrap_it('For further information check out: ' 'http://anvil.readthedocs.org')) buf.write("\n") return buf.getvalue()
def __init__(self): # instance attributes, feels safer self.options = None self.args = None self.__verbose = None self.__verbose_default = 0 self.__timeout = None self.__timeout_default = 10 self.__timeout_max = 86400 self.topfile = get_topfile() # this gets utrunner.py in PyCharm and runpy.py from unittest if os.path.basename(self.topfile) in ('utrunner.py', 'runpy.py'): self.topfile = __file__ #print('topfile = %s' % self.topfile) self._docstring = get_file_docstring(self.topfile) if self._docstring: self._docstring = '\n' + self._docstring.strip() + '\n' if self._docstring is None: self._docstring = '' self._topfile_version = get_file_version(self.topfile) # this doesn't work in unit tests # if self._topfile_version: # raise CodingError('failed to get topfile version - did you set a __version__ in top cli program?') # pylint: disable=line-too-long self._cli_version = self.__version__ self._utils_version = harisekhon.utils.__version__ # returns 'python -m unittest' :-/ # prog = os.path.basename(sys.argv[0]) self._prog = os.path.basename(self.topfile) self._github_repo = get_file_github_repo(self.topfile) # if not self.github_repo: # self.github_repo = 'https://github.com/harisekhon/pytools' if self._github_repo: self._github_repo = ' - ' + self._github_repo # _hidden attributes are shown in __dict__ self.version = '%(_prog)s version %(_topfile_version)s ' % self.__dict__ + \ '=> CLI version %(_cli_version)s => Utils version %(_utils_version)s' % self.__dict__ self.usagemsg = 'Hari Sekhon%(_github_repo)s\n\n%(_prog)s\n%(_docstring)s\n' \ % self.__dict__ self.usagemsg_short = 'Hari Sekhon%(_github_repo)s\n\n' % self.__dict__ # set this in simpler client programs when you don't want to exclude # self.__parser = OptionParser(usage=self.usagemsg_short, version=self.version) # self.__parser = OptionParser(version=self.version) # will be added by default_opts later so that it's not annoyingly at the top of the option help # also this allows us to print full docstring for a complete description and not just the cli switches # description=self._docstring # don't want description printed for option errors width = os.getenv('COLUMNS', None) if not isInt(width) or not width: width = Terminal().width width = min(width, 200) self.__parser = OptionParser(add_help_option=False, formatter=IndentedHelpFormatter(width=width)) # duplicate key error or duplicate options, sucks # self.__parser.add_option('-V', dest='version', help='Show version and exit', action='store_true') self.setup()
def format_option_strings(self, option): """Extend option string formatting to support arguments for commands""" if option.action == 'command' and not option.args == 'no': arg_name = option.metavar or _('indices') if option.args == 'optional': arg_name = ''.join(['[', arg_name, ']']) lopts = [' '.join([lopt, arg_name]) for lopt in option._long_opts] return ', '.join(lopts) else: return IndentedHelpFormatter.format_option_strings(self, option)
def main(): p = OptionParser( "%prog SERVER:/PATH [options] flags|testcodes\n" " %prog --help\n" " %prog SHOWOPTION", formatter=IndentedHelpFormatter(2, 25)) opt, args = scan_options(p) # Create test database tests, fdict, cdict = testmod.createtests('client41tests') # Deal with any informational options if opt.showflags: printflags(fdict.keys()) sys.exit(0) if opt.showcodes: codes = cdict.keys() codes.sort() for c in codes: print c sys.exit(0) # Grab server info and set defaults if not args: p.error("Need a server") url = args.pop(0) print "url", url opt.path = nfs4lib.path_components(url) print "Set opt.path", opt.path # Check --use* options are valid for attr in dir(opt): if attr == 'useparams': opt.useparams = parse_useparams(opt.useparams) elif attr.startswith('use') and attr != "usefh": path = getattr(opt, attr) #print attr, path if path is None: path = opt.path + ['tree', attr[3:]] else: # FIXME - have funct that checks path validity if path[0] != '/': p.error("Need to use absolute path for --%s" % attr) # print path if path[-1] == '/' and attr != 'usedir': p.error("Can't use dir for --%s" % attr) try: path = nfs4lib.path_components(path) except Exception, e: p.error(e) setattr(opt, attr, [comp for comp in path if comp])
def main(): """ The method called when running this script """ usage = """calc_histogram.py --expr "expresion" A command-line tool to test similarity to Microsoft's Academic Knowledge.""" fmt = IndentedHelpFormatter(max_help_position=50, width=100) parser = OptionParser(usage=usage, formatter=fmt) group = OptionGroup( parser, 'Query arguments', 'These options define search query arguments and parameters.') group.add_option('-e', '--expresion', metavar='EXPR', default=None, help='Expression') group.add_option('-a', '--attributes', metavar='ATTR', default='Id', help='Expression') parser.add_option_group(group) options, _ = parser.parse_args() # Show help if we have not an expression if len(sys.argv) == 1: parser.print_help() return 1 if options.expresion is None: print('Expression is mandatory!') return 1 query = inquirer.AcademicQuerier(inquirer.AcademicQueryType.HISTOGRAM, { 'expr': options.expresion, 'attributes': options.attributes }) if query is not None: histograms = query.post() for histogram in histograms: data = histogram['data'] rng = range(1, len(data) + 1) labels = [val['value'] for val in data] plt.bar(rng, [val['count'] for val in data]) plt.xticks(rng, labels, rotation='vertical') plt.margins(0.2) plt.subplots_adjust(bottom=0.15) plt.legend() plt.xlabel(histogram['attribute']) plt.ylabel('count') plt.title('Histogram for {}'.format(histogram['attribute'])) plt.show()
def format_usage(self, usage): buf = StringIO() buf.write(IndentedHelpFormatter.format_usage(self, usage)) buf.write("\n") buf.write(self._wrap_it(OVERVIEW)) buf.write("\n\n") buf.write(self._wrap_it(STEPS)) buf.write("\n\n") for k in sorted(STEP_SECTIONS.keys()): buf.write("%s:\n" % (k.title())) for line in STEP_SECTIONS[k]: buf.write(" %s\n" % (line)) return buf.getvalue()
def __init__(self, prog, usage, args): self.given = args formatter = IndentedHelpFormatter( indent_increment=2, max_help_position=80, width=100, short_first=1) LenientOptionParser.__init__(self, prog=prog, usage=usage, formatter=formatter) self.disable_interspersed_args()
def scan_options(): from optparse import OptionParser, OptionGroup, IndentedHelpFormatter p = OptionParser("%prog [--dport=<?> --port=<?>] --dserver=<?>", formatter = IndentedHelpFormatter(2, 25) ) p.add_option("--dserver", dest="dserver", help="IP address to connect to") p.add_option("--dport", dest="dport", default="2049", type=int, help="Set port to connect to") p.add_option("--port", dest="port", type=int, default="2049", help="Set port to listen on (2049)") opts, args = p.parse_args() if args: p.error("Unhandled argument %r" % args[0]) return opts
def format_help(self, formatter=None): class Positional(object): def __init__(self, args): self.option_groups = [] self.option_list = args positional = Positional(self.positional) formatter = IndentedHelpFormatter() formatter.store_option_strings(positional) output = ['\n', formatter.format_heading("Positional Arguments")] formatter.indent() pos_help = [formatter.format_option(opt) for opt in self.positional] pos_help = [line.replace('--', '') for line in pos_help] output += pos_help return OptionParser.format_help(self, formatter) + ''.join(output)
def option_parser(): from optparse import OptionParser, make_option, IndentedHelpFormatter help_fmt = ('Method of traversing errors and files to use with autopep8; ' 'choose from: {0}; ' 'default is {1}') option_list = [ make_option('-r', '--recurse', dest='recurse', action='store_true', default=False, help='Recurse down directories from STARTDIR'), make_option('-d', '--dryrun', dest='dryrun', action='store_true', default=False, help='Do dry run -- do not modify files'), make_option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Verbose output'), make_option('-a', '--autopep8', dest='autopep8', action='store', default="autopep8", help='Specify path to autopep8 instance'), make_option('-s', '--select', dest='errors', default=None, action='store', help='Select specific errors'), make_option('-m', '--method', dest='method', default=METHODS[0], type="choice", choices=METHODS, help=help_fmt.format(", ".join(METHODS), METHODS[0])), ] return OptionParser(option_list=option_list, formatter=IndentedHelpFormatter(width=60))
def parse_arguments(self): ''' Gets command-line arguments and handles validation ''' parser = OptionParser("%prog [options]", formatter=IndentedHelpFormatter(4, 80)) parser.add_option("-s", "--scale-factor", dest="scale_factor", type="int", help="factor to scale tests by", metavar="NUM", default=1) options, args = parser.parse_args() # pylint: disable=W0612 return options
def format_option(self, option): """Return colorful formatted help for an option.""" option = IndentedHelpFormatter.format_option(self, option) # long options with args option = re.sub( r"--([a-zA-Z]*)=([a-zA-Z]*)", lambda m: "-%s %s" % (output.green(m.group(1)), output.blue(m.group(2))), option) # short options with args option = re.sub( r"-([a-zA-Z]) ?([0-9A-Z]+)", lambda m: " -" + output.green( m.group(1)) + ' ' + output.blue(m.group(2)), option) # options without args option = re.sub(r"-([a-zA-Z?]+)", lambda m: "-" + output.green(m.group(1)), option) return option
def parse_options(): """ Parse command line options """ import version formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [--daemon|--stop]", version='%prog ' + str(version.version)) parser.prog = appname parser.description = "start or stop the commercial detection server" parser.add_option('-d', '--debug', action='store_true', dest='debug', default=False, help='enable debugging') opts, args = parser.parse_args() return opts, args
def format_help(self, formatter=None): class Positional(object): def __init__(self, args): self.option_groups = [] self.option_list = args positional = Positional(self.positional) formatter = IndentedHelpFormatter() formatter.store_option_strings(positional) output = ['\n', formatter.format_heading("Positional Arguments")] formatter.indent() pos_help = [formatter.format_option(opt) for opt in self.positional] pos_help = [line.replace('--','') for line in pos_help] output += pos_help return OptionParser.format_help(self, formatter) + ''.join(output)
def format_option(self, option): """Extend option formatting to include formatting of supported options.""" result = IndentedHelpFormatter.format_option(self, option) if option.action == 'command' and option.options: options = ', '.join(option.options) msg = _('Supported options: ') # build the complete options string and wrap it to width of the # help opt_str = ''.join((msg, options)) initial_indent = ' '*(self.help_position + 4) subsequent_indent = ' '*(self.help_position + 4 + len(msg)) width = self.help_position + self.help_width opt_str = textwrap.fill(opt_str, width, initial_indent=initial_indent, subsequent_indent=subsequent_indent) result += opt_str + '\n' return result
def format_option(self, option): """Return colorful formatted help for an option.""" option = IndentedHelpFormatter.format_option(self, option) # long options with args option = re.sub( r"--([a-zA-Z]*)=([a-zA-Z]*)", lambda m: "-%s %s" % (self.output.green(m.group(1)), self.output.blue(m.group(2))), option) # short options with args option = re.sub( r"-([a-zA-Z]) ?([0-9A-Z]+)", lambda m: " -" + self.output.green(m.group(1)) + ' ' + \ self.output.blue(m.group(2)), option) # options without args option = re.sub( r"-([a-zA-Z\d]+)", lambda m: "-" + self.output.green(m.group(1)), option) return option
def format_option(self, option): """Extend option formatting to include formatting of supported options.""" result = IndentedHelpFormatter.format_option(self, option) if option.action == 'command' and option.options: options = ', '.join(option.options) msg = _('Supported options: ') # make sure we have the correct length # (and are not counting unicode double-bytes twice, which would # break length calculation e.g. for german umlauts msg_len = len(msg.decode(_STDOUT_ENCODING)) # build the complete options string and wrap it to width of the # help opt_str = ''.join([msg, options]) initial_indent = ' '*(self.help_position + 4) subsequent_indent = ' '*(self.help_position + 4 + msg_len) width = self.help_position + self.help_width opt_str = textwrap.fill(opt_str, width, initial_indent=initial_indent, subsequent_indent=subsequent_indent) result += opt_str + '\n' return result
def __init__(self, metavar_format=' <{}>', metavar_column=None, option_separator=', ', align_long_opts=False, help_string_formatter=None, preformatted_description=True, preformatted_epilog=True, *args, **kw): """ :arg metavar_format: Evaluated as `metavar_format.format(metavar)` if string. If callable, evaluated as `metavar_format(metavar)`. :arg metavar_column: Column to which all metavars should be aligned. :arg option_separator: String between short and long option. E.g: ', ' -> '-f, --format'. :arg align_long_opts: Align all long options on the current indent level to the same column. For example: align_long_opts=False align_long_opts=True -------------------------- -------------------------- -h, --help show this ... -h, --help show this ... --fast avoid slow ... --fast avoid slow ... :arg help_string_format: Function to call to call on help string after expansion. Called as `help_string_format(help, option)`. :arg preformatted_description: If True, description will be displayed as-is, instead of text-wrapping it first. :arg preformatted_description: If True, epilog will be displayed as-is, instead of text-wrapping it first. :arg width: Maximum help message width. Defaults to 78 unless $COLUMNS is set. """ if not callable(metavar_format): func = partial(format_option_metavar, fmt=metavar_format) else: func = metavar_format self.metavar_format = func self.metavar_column = metavar_column self.align_long_opts = align_long_opts self.option_separator = option_separator self.help_string_formatter = help_string_formatter if 'width' not in kw: try: kw['width'] = int(os.environ['COLUMNS']) - 2 except (KeyError, ValueError): kw['width'] = 78 kw['max_help_position'] = kw.get('max_help_position', kw['width']) kw['indent_increment'] = kw.get('indent_increment', 1) kw['short_first'] = kw.get('short_first', 1) # leave full control of description and epilog to us self.preformatted_description = preformatted_description self.preformatted_epilog = preformatted_epilog IndentedHelpFormatter.__init__(self, *args, **kw)
def expand_default(self, option): ret = IndentedHelpFormatter.expand_default(self, option) if isinstance(option, ExpertOption): ret = "(Advanced) " + ret return ret.replace(self.choices_tag, ", ".join(option.choices or []))
def __init__(self, *args, **kwargs): IndentedHelpFormatter.__init__(self, *args, **kwargs) self.help_position = 0
def _format_text(self, text): paragraphs = text.split('\n\n') return '\n\n'.join(IndentedHelpFormatter._format_text(self, p) for p in paragraphs)
def format_usage(self, usage): msg = IndentedHelpFormatter.format_usage(self, usage) return '%s\n%s' % (self.banner, msg)
def __init__(self, *args, **kwargs): IndentedHelpFormatter.__init__(self, *args, **kwargs)
def __init__(self): # indent incr, max_help_pos, width, short_first IndentedHelpFormatter.__init__(self, 2, 26, None, 1)
def format_description(self, description): if self.preformatted_description: return description if description else '' else: return IndentedHelpFormatter.format_description(self, description)
def __init__(self, heading): self.heading = heading IndentedHelpFormatter.__init__(self)
def format_option(self, text): textwrap.wrap, old = wrap_with_newlines, textwrap.wrap result = IndentedHelpFormatter.format_option(self, text) textwrap.wrap = old return result
def __init__(self, banner, *argv, **argd): self.banner = banner IndentedHelpFormatter.__init__(self, *argv, **argd)
def __init__(self, *args, **kwargs): IndentedHelpFormatter.__init__(self, *args, **kwargs) self.envvar_tag = "%envvar"
def format_epilog(self, epilog): if self.preformatted_epilog: return epilog if epilog else '' else: return IndentedHelpFormatter.format_epilog(self, epilog)
def __init__(self, subcommand_arg_summaries, *args, **kwargs): self.subcommand_arg_summaries = subcommand_arg_summaries IndentedHelpFormatter.__init__(self, *args, **kwargs)
def format_epilog(self, epilog): formatted_epilog = IndentedHelpFormatter.format_epilog(self, epilog) summaries = self.subcommand_arg_summaries() return ('%s\nSubcommands:\n%s\n' % (formatted_epilog, summaries) if summaries else formatted_epilog)
def expand_default(self, option): if hasattr(option, 'envvar') and hasattr(option, 'help'): option.help = option.help.replace(str(self.envvar_tag), "$" + str(option.envvar)) return IndentedHelpFormatter.expand_default(self, option)
def __init__(self): IndentedHelpFormatter.__init__(self)
def expand_default(self, option): help = IndentedHelpFormatter.expand_default(self, option) if callable(self.help_string_formatter): return self.help_string_formatter(help, option) return help