Python argparse.HelpFormatter() Examples
The following are 30
code examples of argparse.HelpFormatter().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
argparse
, or try the search function
.
Example #1
Source File: args.py From wifite2mod with GNU General Public License v2.0 | 7 votes |
def get_arguments(self): ''' Returns parser.args() containing all program arguments ''' parser = argparse.ArgumentParser(usage=argparse.SUPPRESS, formatter_class=lambda prog: argparse.HelpFormatter( prog, max_help_position=80, width=130)) self._add_global_args(parser.add_argument_group(Color.s('{C}SETTINGS{W}'))) self._add_wep_args(parser.add_argument_group(Color.s('{C}WEP{W}'))) self._add_wpa_args(parser.add_argument_group(Color.s('{C}WPA{W}'))) self._add_wps_args(parser.add_argument_group(Color.s('{C}WPS{W}'))) self._add_pmkid_args(parser.add_argument_group(Color.s('{C}PMKID{W}'))) self._add_eviltwin_args(parser.add_argument_group(Color.s('{C}EVIL TWIN{W}'))) self._add_command_args(parser.add_argument_group(Color.s('{C}COMMANDS{W}'))) return parser.parse_args()
Example #2
Source File: filter.py From inferbeddings with MIT License | 6 votes |
def main(argv): def formatter(prog): return argparse.HelpFormatter(prog, max_help_position=100, width=200) argparser = argparse.ArgumentParser('Filtering tool for filtering away infrequent entities from Knowledge Graphs', formatter_class=formatter) argparser.add_argument('triples', type=str, help='File containing triples') argparser.add_argument('entities', type=str, help='File containing entities') args = argparser.parse_args(argv) triples_path = args.triples entities_path = args.entities triples = read_triples(triples_path) with iopen(entities_path, mode='r') as f: entities = set([line.strip() for line in f.readlines()]) for (s, p, o) in triples: if s in entities and o in entities: print("%s\t%s\t%s" % (s, p, o))
Example #3
Source File: params.py From BLINK with MIT License | 6 votes |
def __init__( self, add_blink_args=True, add_model_args=False, description='BLINK parser', ): super().__init__( description=description, allow_abbrev=False, conflict_handler='resolve', formatter_class=argparse.HelpFormatter, add_help=add_blink_args, ) self.blink_home = os.path.dirname( os.path.dirname(os.path.dirname(os.path.realpath(__file__))) ) os.environ['BLINK_HOME'] = self.blink_home self.add_arg = self.add_argument self.overridable = {} if add_blink_args: self.add_blink_args() if add_model_args: self.add_model_args()
Example #4
Source File: shell.py From eclcli with Apache License 2.0 | 6 votes |
def _find_actions(self, subparsers, actions_module): for attr in (a for a in dir(actions_module) if a.startswith('do_')): # I prefer to be hyphen-separated instead of underscores. command = attr[3:].replace('_', '-') callback = getattr(actions_module, attr) desc = callback.__doc__ or '' help = desc.strip().split('\n')[0] arguments = getattr(callback, 'arguments', []) subparser = subparsers.add_parser(command, help=help, description=desc, add_help=False, formatter_class=HelpFormatter) subparser.add_argument('-h', '--help', action='help', help=argparse.SUPPRESS) self.subcommands[command] = subparser for (args, kwargs) in arguments: subparser.add_argument(*args, **kwargs) subparser.set_defaults(func=callback)
Example #5
Source File: __init__.py From freepacktbook with MIT License | 6 votes |
def download_parser(description): class SortedHelpFormatter(HelpFormatter): def add_arguments(self, actions): actions = sorted(actions, key=attrgetter("option_strings")) super(SortedHelpFormatter, self).add_arguments(actions) parser = ArgumentParser( description=description, formatter_class=SortedHelpFormatter ) parser.add_argument("--force", action="store_true", help="override existing files") parser.add_argument( "--formats", nargs="+", metavar="FORMAT", help="ebook formats (epub, mobi, pdf)" ) parser.add_argument( "--with-code-files", action="store_true", help="download code files" ) return parser
Example #6
Source File: filter.py From inferbeddings with MIT License | 6 votes |
def main(argv): def formatter(prog): return argparse.HelpFormatter(prog, max_help_position=100, width=200) argparser = argparse.ArgumentParser('Filtering tool for filtering away infrequent entities from Knowledge Graphs', formatter_class=formatter) argparser.add_argument('triples', type=str, help='File containing triples') argparser.add_argument('entities', type=str, help='File containing entities') args = argparser.parse_args(argv) triples_path = args.triples entities_path = args.entities triples = read_triples(triples_path) with iopen(entities_path, mode='r') as f: entities = set([line.strip() for line in f.readlines()]) for (s, p, o) in triples: if s in entities and o in entities: print("%s\t%s\t%s" % (s, p, o))
Example #7
Source File: filter.py From inferbeddings with MIT License | 6 votes |
def main(argv): def formatter(prog): return argparse.HelpFormatter(prog, max_help_position=100, width=200) argparser = argparse.ArgumentParser('Filtering tool for filtering away infrequent entities from Knowledge Graphs', formatter_class=formatter) argparser.add_argument('triples', type=str, help='File containing triples') argparser.add_argument('entities', type=str, help='File containing entities') args = argparser.parse_args(argv) triples_path = args.triples entities_path = args.entities triples = read_triples(triples_path) with iopen(entities_path, mode='r') as f: entities = set([line.strip() for line in f.readlines()]) for (s, p, o) in triples: if s in entities and o in entities: print("%s\t%s\t%s" % (s, p, o))
Example #8
Source File: utils.py From spinalcordtoolbox with MIT License | 6 votes |
def _split_lines(self, text, width): if text.startswith('R|'): lines = text[2:].splitlines() offsets = [re.match("^[ \t]*", l).group(0) for l in lines] wrapped = [] for i in range(len(lines)): li = lines[i] o = offsets[i] ol = len(o) init_wrap = argparse._textwrap.fill(li, width).splitlines() first = init_wrap[0] rest = "\n".join(init_wrap[1:]) rest_wrap = argparse._textwrap.fill(rest, width - ol).splitlines() offset_lines = [o + wl for wl in rest_wrap] wrapped = wrapped + [first] + offset_lines return wrapped return argparse.HelpFormatter._split_lines(self, text, width)
Example #9
Source File: cli.py From lbry-sdk with MIT License | 6 votes |
def __init__(self, *args, group_name=None, **kwargs): super().__init__(*args, formatter_class=HelpFormatter, add_help=False, **kwargs) self.add_argument( '--help', dest='help', action='store_true', default=False, help='Show this help message and exit.' ) self._optionals.title = 'Options' if group_name is None: self.epilog = ( f"Run 'lbrynet COMMAND --help' for more information on a command or group." ) else: self.epilog = ( f"Run 'lbrynet {group_name} COMMAND --help' for more information on a command." ) self.set_defaults(group=group_name, group_parser=self)
Example #10
Source File: nli-query-cli.py From inferbeddings with MIT License | 6 votes |
def main(argv): def formatter(prog): return argparse.HelpFormatter(prog, max_help_position=100, width=200) argparser = argparse.ArgumentParser('NLI Client', formatter_class=formatter) argparser.add_argument('s1', action='store', type=str) argparser.add_argument('s2', action='store', type=str) argparser.add_argument('--url', '-u', action='store', type=str, default='http://127.0.0.1:8889/v1/nli') args = argparser.parse_args(argv) sentence1 = args.s1 sentence2 = args.s2 url = args.url prediction = call_service(url=url, sentence1=sentence1, sentence2=sentence2) print(prediction)
Example #11
Source File: shell.py From eclcli with Apache License 2.0 | 6 votes |
def _find_actions(self, subparsers, actions_module): for attr in (a for a in dir(actions_module) if a.startswith('do_')): # I prefer to be hypen-separated instead of underscores. command = attr[3:].replace('_', '-') callback = getattr(actions_module, attr) desc = callback.__doc__ or '' help = desc.strip().split('\n')[0] arguments = getattr(callback, 'arguments', []) subparser = subparsers.add_parser(command, help=help, description=desc, add_help=False, formatter_class=HelpFormatter) subparser.add_argument('-h', '--help', action='help', help=argparse.SUPPRESS) self.subcommands[command] = subparser for (args, kwargs) in arguments: subparser.add_argument(*args, **kwargs) subparser.set_defaults(func=callback)
Example #12
Source File: filter.py From inferbeddings with MIT License | 6 votes |
def main(argv): def formatter(prog): return argparse.HelpFormatter(prog, max_help_position=100, width=200) argparser = argparse.ArgumentParser('Filtering tool for filtering away infrequent entities from Knowledge Graphs', formatter_class=formatter) argparser.add_argument('triples', type=str, help='File containing triples') argparser.add_argument('entities', type=str, help='File containing entities') args = argparser.parse_args(argv) triples_path = args.triples entities_path = args.entities triples = read_triples(triples_path) with iopen(entities_path, mode='r') as f: entities = set([line.strip() for line in f.readlines()]) for (s, p, o) in triples: if s in entities and o in entities: print("%s\t%s\t%s" % (s, p, o))
Example #13
Source File: primefaces.py From CVE-2017-1000486 with GNU General Public License v3.0 | 6 votes |
def get_args(): parser = argparse.ArgumentParser( prog="primefaces.py", formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=50), epilog= ''' This script exploits an expression language remote code execution flaw in the Primefaces JSF framework. Primefaces versions prior to 5.2.21, 5.3.8 or 6.0 are vulnerable to a padding oracle attack, due to the use of weak crypto and default encryption password and salt. ''') parser.add_argument("target", help="Target Host") parser.add_argument("-pw", "--password", default="primefaces", help="Primefaces Password (Default = primefaces") parser.add_argument("-pt", "--path", default="/javax.faces.resource/dynamiccontent.properties.xhtml", help="Path to dynamiccontent.properties (Default = /javax.faces.resource/dynamiccontent.properties.xhtml)") parser.add_argument("-c", "--cmd", default="whoami", help="Command to execute. (Default = whoami)") parser.add_argument("-px", "--proxy", default="", help="Configure a proxy in the format http://127.0.0.1:8080/ (Default = None)") parser.add_argument("-ck", "--cookie", default="", help="Configure a cookie in the format 'COOKIE=VALUE; COOKIE2=VALUE2;' (Default = None)") parser.add_argument("-o", "--oracle", default="0", help="Exploit the target with Padding Oracle. Use 1 to activate. (Default = 0) (SLOW)") parser.add_argument("-pl", "--payload", default="", help="EL Encrypted payload. That function is meant to be used with the Padding Oracle generated payload. (Default = None) ") args = parser.parse_args() return args
Example #14
Source File: args.py From faceswap with GNU General Public License v3.0 | 6 votes |
def _split_lines(self, text, width): """ Split the given text by the given display width. If the text is not prefixed with "R|" then the standard :func:`argparse.HelpFormatter._split_lines` function is used, otherwise raw formatting is processed, Parameters ---------- text: str The help text that is to be formatted for display width: int The display width, in characters, for the help text """ if text.startswith("R|"): text = self._whitespace_matcher_limited.sub(' ', text).strip()[2:] output = list() for txt in text.splitlines(): indent = "" if txt.startswith("L|"): indent = " " txt = " - {}".format(txt[2:]) output.extend(textwrap.wrap(txt, width, subsequent_indent=indent)) return output return argparse.HelpFormatter._split_lines(self, text, width)
Example #15
Source File: test_argparse.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_parser(self): parser = argparse.ArgumentParser(prog='PROG') string = ( "ArgumentParser(prog='PROG', usage=None, description=None, " "version=None, formatter_class=%r, conflict_handler='error', " "add_help=True)" % argparse.HelpFormatter) self.assertStringEqual(parser, string) # =============== # Namespace tests # ===============
Example #16
Source File: argparsing.py From pytest with MIT License | 5 votes |
def _format_action_invocation(self, action: argparse.Action) -> str: orgstr = argparse.HelpFormatter._format_action_invocation(self, action) if orgstr and orgstr[0] != "-": # only optional arguments return orgstr res = getattr( action, "_formatted_action_invocation", None ) # type: Optional[str] if res: return res options = orgstr.split(", ") if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2): # a shortcut for '-h, --help' or '--abc', '-a' action._formatted_action_invocation = orgstr # type: ignore return orgstr return_list = [] short_long = {} # type: Dict[str, str] for option in options: if len(option) == 2 or option[2] == " ": continue if not option.startswith("--"): raise ArgumentError( 'long optional argument without "--": [%s]' % (option), option ) xxoption = option[2:] shortened = xxoption.replace("-", "") if shortened not in short_long or len(short_long[shortened]) < len( xxoption ): short_long[shortened] = xxoption # now short_long has been filled out to the longest with dashes # **and** we keep the right option ordering from add_argument for option in options: if len(option) == 2 or option[2] == " ": return_list.append(option) if option[2:] == short_long.get(option.replace("-", "")): return_list.append(option.replace(" ", "=", 1)) formatted_action_invocation = ", ".join(return_list) action._formatted_action_invocation = formatted_action_invocation # type: ignore return formatted_action_invocation
Example #17
Source File: help_formatter.py From Deepbinner with GNU General Public License v3.0 | 5 votes |
def _split_lines(self, text, width): """ Override this method to add special behaviour for help texts that start with: 'B|' - loop text to the column of the equals sign 'R|' - loop text one option per line """ if text.startswith('B|') or text.startswith('R|'): text_lines = text[2:].splitlines() wrapped_text_lines = [] for line in text_lines: if len(line) <= width: wrapped_text_lines.append(line) else: wrap_column = 2 if text.startswith('B|'): line_parts = line.split() wrap_column += line.find('=') join = '' current_line = ' ' + line_parts[0] else: # text.startswith('R|') line_parts = line.split(', ') join = ',' current_line = line_parts[0] for part in line_parts[1:]: if len(current_line) + len(join) + 1 + len(part) <= width: current_line += join + ' ' + part else: wrapped_text_lines.append(current_line + join) current_line = ' ' * wrap_column + part wrapped_text_lines.append(current_line) return wrapped_text_lines else: return argparse.HelpFormatter._split_lines(self, text, width)
Example #18
Source File: DumpsterDiver.py From DumpsterDiver with MIT License | 5 votes |
def _split_lines(self, text, width): if text.startswith('R|'): return text[2:].splitlines() # this is the RawTextHelpFormatter._split_lines return argparse.HelpFormatter._split_lines(self, text, width)
Example #19
Source File: shell.py From eclcli with Apache License 2.0 | 5 votes |
def start_section(self, heading): # Title-case the headings heading = '%s%s' % (heading[0].upper(), heading[1:]) super(HelpFormatter, self).start_section(heading)
Example #20
Source File: __main__.py From panaroo with MIT License | 5 votes |
def _split_lines(self, text, width): if text.startswith('R|'): lines = [] for l in text[2:].splitlines(): if l == "": lines += [""] else: lines += textwrap.wrap(l, width=55) return lines # this is the RawTextHelpFormatter._split_lines return argparse.HelpFormatter._split_lines(self, text, width)
Example #21
Source File: test_argparse.py From oss-ftp with MIT License | 5 votes |
def test_parser(self): parser = argparse.ArgumentParser(prog='PROG') string = ( "ArgumentParser(prog='PROG', usage=None, description=None, " "version=None, formatter_class=%r, conflict_handler='error', " "add_help=True)" % argparse.HelpFormatter) self.assertStringEqual(parser, string) # =============== # Namespace tests # ===============
Example #22
Source File: shell.py From eclcli with Apache License 2.0 | 5 votes |
def start_section(self, heading): # Title-case the headings heading = '%s%s' % (heading[0].upper(), heading[1:]) super(HelpFormatter, self).start_section(heading)
Example #23
Source File: shell.py From eclcli with Apache License 2.0 | 5 votes |
def __init__(self, prog, indent_increment=2, max_help_position=32, width=None): super(HelpFormatter, self).__init__(prog, indent_increment, max_help_position, width)
Example #24
Source File: shell.py From eclcli with Apache License 2.0 | 5 votes |
def _add_bash_completion_subparser(self, subparsers): subparser = subparsers.add_parser( 'bash_completion', add_help=False, formatter_class=HelpFormatter ) self.subcommands['bash_completion'] = subparser subparser.set_defaults(func=self.do_bash_completion)
Example #25
Source File: __init__.py From pyiron with BSD 3-Clause "New" or "Revised" License | 5 votes |
def main(): parser = argparse.ArgumentParser(prog = "pyiron", description = __doc__) parser.add_argument( "-d", "--dirty", action = "store_true", help = "do not remove pyiron log files" ) subs = parser.add_subparsers() parser.set_defaults(cli = lambda _: parser.error("no sub command given")) for name, mod in cli_modules.items(): try: sub_parser = subs.add_parser(name, help = mod.__doc__, description = mod.__doc__, epilog = getattr(mod, "epilog", None), formatter_class = getattr(mod, "formatter", argparse.HelpFormatter) ) sub_parser.set_defaults(cli = mod.main) mod.register(sub_parser) except AttributeError: warnings.warn("module '{}' does not define main or register " "function, ignoring") args = parser.parse_args() args.cli(args) if not args.dirty: os.remove("pyiron.log")
Example #26
Source File: common.py From nrf24-playset with GNU General Public License v3.0 | 5 votes |
def init_args(description): global parser parser = argparse.ArgumentParser(description, formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=50,width=120)) parser.add_argument('-c', '--channels', type=int, nargs='+', help='RF channels', default=range(2, 84), metavar='N') parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose output', default=False) parser.add_argument('-l', '--lna', action='store_true', help='Enable the LNA (for CrazyRadio PA dongles)', default=False) parser.add_argument('-i', '--index', type=int, help='Dongle index', default=0) # Parse and process common comand line arguments
Example #27
Source File: sphinxext.py From cliff with Apache License 2.0 | 5 votes |
def _format_usage(parser): """Get usage without a prefix.""" fmt = argparse.HelpFormatter(parser.prog) optionals = parser._get_optional_actions() positionals = parser._get_positional_actions() groups = parser._mutually_exclusive_groups # hacked variant of the regex used by the actual argparse module. Unlike # that version, this one attempts to group long and short opts with their # optional arguments ensuring that, for example, '--format <FORMAT>' # becomes ['--format <FORMAT>'] and not ['--format', '<FORMAT>']. # Yes, they really do use regexes to break apart and rewrap their help # string. Don't ask me why. part_regexp = re.compile(r""" \(.*?\)+ | \[.*?\]+ | (?:(?:-\w|--\w+(?:-\w+)*)(?:\s+<?\w[\w-]*>?)?) | \S+ """, re.VERBOSE) opt_usage = fmt._format_actions_usage(optionals, groups) pos_usage = fmt._format_actions_usage(positionals, groups) opt_parts = part_regexp.findall(opt_usage) pos_parts = part_regexp.findall(pos_usage) parts = opt_parts + pos_parts if len(' '.join([parser.prog] + parts)) < 72: return [' '.join([parser.prog] + parts)] return [parser.prog] + [_indent(x) for x in parts]
Example #28
Source File: utility.py From signac with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _split_lines(self, text, width): if text.startswith('R|'): return text[2:].splitlines() return argparse.HelpFormatter._split_lines(self, text, width)
Example #29
Source File: util.py From btrfs-backup with MIT License | 5 votes |
def _split_lines(self, text, width): if text.startswith("N|"): _lines = text[2:].splitlines() else: _lines = [text] lines = [] for line in _lines: # this is the RawTextHelpFormatter._split_lines lines.extend(argparse.HelpFormatter._split_lines(self, line, width)) return lines
Example #30
Source File: argparsing.py From python-netsurv with MIT License | 5 votes |
def _format_action_invocation(self, action): orgstr = argparse.HelpFormatter._format_action_invocation(self, action) if orgstr and orgstr[0] != "-": # only optional arguments return orgstr res = getattr(action, "_formatted_action_invocation", None) if res: return res options = orgstr.split(", ") if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2): # a shortcut for '-h, --help' or '--abc', '-a' action._formatted_action_invocation = orgstr return orgstr return_list = [] option_map = getattr(action, "map_long_option", {}) if option_map is None: option_map = {} short_long = {} for option in options: if len(option) == 2 or option[2] == " ": continue if not option.startswith("--"): raise ArgumentError( 'long optional argument without "--": [%s]' % (option), self ) xxoption = option[2:] if xxoption.split()[0] not in option_map: shortened = xxoption.replace("-", "") if shortened not in short_long or len(short_long[shortened]) < len( xxoption ): short_long[shortened] = xxoption # now short_long has been filled out to the longest with dashes # **and** we keep the right option ordering from add_argument for option in options: if len(option) == 2 or option[2] == " ": return_list.append(option) if option[2:] == short_long.get(option.replace("-", "")): return_list.append(option.replace(" ", "=", 1)) action._formatted_action_invocation = ", ".join(return_list) return action._formatted_action_invocation