max_help_position在python argparse库中不起作用

Ale*_*nko 5 python argparse

嗨同事我有代码(max_help_position是2000):

formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=2000)
parser = argparse.ArgumentParser(formatter_class=formatter_class)


subparsers = parser.add_subparsers(title="Commands", metavar="<command>")

cmd_parser = subparsers.add_parser('long_long_long_long_long_long_long',
                                   help='- jksljdalkjda',
                                   formatter_class=formatter_class)

args = parser.parse_args(['-h'])
print args
Run Code Online (Sandbox Code Playgroud)

我们有

optional arguments:
  -h, --help                          show this help message and exit

Commands:
  <command>
    long_long_long_long_long_long_long
                                      - jksljdalkjda
    small                             - descr
Run Code Online (Sandbox Code Playgroud)

代替

optional arguments:
  -h, --help  show this help message and exit

Commands:
  <command>
    long_long_long_long_long_long_long - jksljdalkjda
    small                              - descr
Run Code Online (Sandbox Code Playgroud)

你知道如何解决这个问题吗?

代码:

class MyFormatter(argparse.HelpFormatter):
    def __init__(self, prog):
        super(MyFormatter, self).__init__(prog, max_help_position=2000)
        self._max_help_position = 2000
        self._action_max_length += 4

formatter_class = MyFormatter
parser = argparse.ArgumentParser(formatter_class=formatter_class)
Run Code Online (Sandbox Code Playgroud)

结果相同.

代码(宽度= 2000)

formatter_class = lambda prog: argparse.HelpFormatter(prog,
                  max_help_position=2000, width=2000)
Run Code Online (Sandbox Code Playgroud)

结果相同.

谢谢.

PS还有一些额外的小问题:这是"可选参数"中的奇数空格.你知道如何分离"命令"和"可选参数",因为"可选参数"中没有空格,并且"命令"中有空格,因为它们是不同的本质?

hpa*_*ulj 8

你也需要增加宽度

尝试:

formatter_class=lambda prog: argparse.HelpFormatter(prog,
    max_help_position=100, width=200)
Run Code Online (Sandbox Code Playgroud)

正如我之前的想法(如下)所示,格式化考虑了整体宽度以及max_position值.


(早)

在我的有限测试中,您的格式化器子类似乎有效.但我没有突破极限.

您需要更多地了解Formatter代码.

例如,有一种format_action实际使用max_width的方法

def _format_action(self, action):
    # determine the required width and the entry label
    help_position = min(self._action_max_length + 2,
                        self._max_help_position)
    help_width = self._width - help_position
    action_width = help_position - self._current_indent - 2
    ...
Run Code Online (Sandbox Code Playgroud)

请注意,它与宽度交互.然后它继续实际格式化帮助行并执行包装.所以实际的实现并不简单.

我没有关注你关于空间的问题. format_help命令格式化程序格式化多个部分(包括参数组).这些部分(通常)以两个换行符结束.在组装它们时,格式化程序删除"不必要的"换行符,在组之间留下一个空格.subparser不适合其他类别,因此我必须研究代码以确切了解它是如何处理的.


你的lambda定义也适用.我之前没有见过它,我认为这不是开发人员的意图,而是Python并不重要 - 如果它有效.

使用值和字符串,我看到max_position最多约56个工作.然后它有点棒.但如果我也改变width(默认来自CONSOLE),我可以进一步增加max_position.


我用一个长期的parser论证来测试这个.添加

parser.add_argument('-l','--long','--longlonglonglong', help='help after long option strings')
Run Code Online (Sandbox Code Playgroud)

生产:

usage: issue25297.py [-h] [-l LONG] <command> ...

optional arguments:
  -h, --help                                     show this help message and
                                                 exit
  -l LONG, --long LONG, --longlonglonglong LONG  help after long option
                                                 strings

Commands:
  <command>
    long_long_long_long_long_long_long           - jksljdalkjda
Run Code Online (Sandbox Code Playgroud)

那么max_help_position在常规解析器格式化中也能工作.但由于某种原因,当只有subparser名称很长时,它不会.该部分需要一些特殊的格式.它是缩进的,subparser名称不是真正的动作(参数),而是选择subparsers参数.我会更详细地研究它.

subparser name字符串缩进了2个额外字符(与其他参数相比).收集的代码self._action_max_length不会考虑这一点.因此,如果subparser名称是最长的字符串,则此max_length将最终缩短2个空格.比较实际v所需:

long_long_long_long_long_long_long
                                  - jksljdalkjda
long_long_long_long_long_long_long  - jksljdalkjda
Run Code Online (Sandbox Code Playgroud)

(格式化分两步完成;一次计算这样的值_action_max_length,第二次计算产生实际输出).

Subparsers的格式是递归调用_format_action,所以我对一个简单的修复并不乐观.


更正了格式化程序

这是一个修补的Formatter,它正确地解释了子动作(子解析器)的缩进.当一个参数(action)被添加到Formatter时,该函数会计算其调用字符串的宽度,并调整self._max_action_length.后者使用它来缩进帮助字符串.

class MyFormatter(argparse.HelpFormatter):
    """
    Corrected _max_action_length for the indenting of subactions
    """
    def add_argument(self, action):
        if action.help is not argparse.SUPPRESS:

            # find all invocations
            get_invocation = self._format_action_invocation
            invocations = [get_invocation(action)]
            current_indent = self._current_indent
            for subaction in self._iter_indented_subactions(action):
                # compensate for the indent that will be added
                indent_chg = self._current_indent - current_indent
                added_indent = 'x'*indent_chg
                invocations.append(added_indent+get_invocation(subaction))
            # print('inv', invocations)

            # update the maximum item length
            invocation_length = max([len(s) for s in invocations])
            action_length = invocation_length + self._current_indent
            self._action_max_length = max(self._action_max_length,
                                          action_length)

            # add the item to the list
            self._add_item(self._format_action, [action])
Run Code Online (Sandbox Code Playgroud)

它的一个使用示例(没有真正的广泛):

# call class with alternate parameters
formatter_class=lambda prog: MyFormatter(prog, max_help_position=40,width=100)

parser = argparse.ArgumentParser(formatter_class=formatter_class)

parser.add_argument('-l','--long', help='help after long option strings')

subparsers = parser.add_subparsers(title="Commands", metavar="<command>")

cmd_parser = subparsers.add_parser('long_long_cmd',
                                   help='longish command',
                                   formatter_class=formatter_class,
                                   aliases=['long', 'long_cmd'])
                                   # newer arpgarse take aliases
sht_parser = subparsers.add_parser('short', help = 'short cmd')

args = parser.parse_args(['-h'])
Run Code Online (Sandbox Code Playgroud)

显示:

usage: issue25297.py [-h] [-l LONG] <command> ...

optional arguments:
  -h, --help                        show this help message and exit
  -l LONG, --long LONG              help after long option strings

Commands:
  <command>
    long_long_cmd (long, long_cmd)  longish command
    short                           short cmd
Run Code Online (Sandbox Code Playgroud)