我在我的程序中使用 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/