python - Argparse 子解析器 : hide metavar in command listing

标签 python argparse

我在我的程序中使用 Python argparse 模块作为命令行子命令。我的代码基本上是这样的:

import argparse

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(title="subcommands", metavar="<command>")

subparser = subparsers.add_parser("this", help="do this")
subparser = subparsers.add_parser("that", help="do that")

parser.parse_args()

运行“python test.py --help”时,我想列出可用的子命令。目前我得到这个输出:

usage: test.py [-h] <command> ...

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

subcommands:
  <command>
    this      do this
    that      do that

我能以某种方式删除 <command> 吗?子命令列表中的行并仍将其保留在用法行中?我试图将 help=argparse.SUPPRESS 作为参数提供给 add_subparsers,但这只是隐藏了帮助输出中的所有子命令。

最佳答案

我通过添加一个新的 HelpFormatter 解决了这个问题,如果格式化 PARSER 操作,它只删除该行:

class SubcommandHelpFormatter(argparse.RawDescriptionHelpFormatter):
    def _format_action(self, action):
        parts = super(argparse.RawDescriptionHelpFormatter, self)._format_action(action)
        if action.nargs == argparse.PARSER:
            parts = "\n".join(parts.split("\n")[1:])
        return parts

关于python - Argparse 子解析器 : hide metavar in command listing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13423540/

相关文章:

python - 我将如何进行自定义 Pandas 数据框合并?

python - ipython 笔记本和 ginput

python - 从多进程切换到多线程 Dask.DataFrame

Python:argparse 获取可变大小的列表

Python argparse : how to detect duplicated optional argument?

python - 带有预处理器和小写字母的 sklearn CountVectorizer 中的错误?

python - 如何在不使用 eval() 或 exec() 的情况下创建规则引擎?

python - argparse 有没有办法允许第一个位置参数不仅是无破折号,而且是多个可能的用户输入值之一?

python - 保存python argparse文件

python argparse : force argument sequence