(parser, help_width=32)
| 15 | import textwrap |
| 16 | |
| 17 | def print_parser(parser, help_width=32): |
| 18 | argument_list = [] |
| 19 | |
| 20 | for action in parser._actions: |
| 21 | if isinstance(action, argparse._SubParsersAction): |
| 22 | continue |
| 23 | if '--help' in action.option_strings: |
| 24 | continue |
| 25 | |
| 26 | arg_name = ', '.join([opt.lstrip('-') for opt in action.option_strings]) |
| 27 | arg_help = action.help or '' |
| 28 | arg_type = action.type.__name__ if action.type else 'str' |
| 29 | arg_default = str(action.default) if action.default is not None else 'None' |
| 30 | |
| 31 | argument_list.append((arg_name, arg_help, arg_type, arg_default)) |
| 32 | |
| 33 | max_name_len = max([len(arg[0]) for arg in argument_list]) |
| 34 | |
| 35 | print("-" * (max_name_len + 56)) |
| 36 | print(f"{'Argument'.ljust(max_name_len)} Help" + " "*(help_width-4) + f"{'Type'.ljust(8)} Default") |
| 37 | print("-" * (max_name_len + 56)) |
| 38 | |
| 39 | wrapper = textwrap.TextWrapper(width=help_width) |
| 40 | |
| 41 | for arg_name, arg_help, arg_type, arg_default in argument_list: |
| 42 | name_str = arg_name.ljust(max_name_len) |
| 43 | type_str = arg_type.ljust(8) |
| 44 | |
| 45 | wrapped_help = wrapper.wrap(arg_help) |
| 46 | if not wrapped_help: |
| 47 | wrapped_help = [''] |
| 48 | |
| 49 | for i, line in enumerate(wrapped_help): |
| 50 | if i == 0: |
| 51 | print(f"{name_str} {line.ljust(help_width)} {type_str} {arg_default}") |
| 52 | else: |
| 53 | print(f"{''.ljust(max_name_len)} {line.ljust(help_width)}") |
| 54 | print() |
| 55 | |
| 56 | def print_aligned_string_list(str_list, column_spacing=2): |
| 57 | # 获取字符串列表中的最长字符串长度 |
no test coverage detected