在 argparse 中,是否可以将 -h 选项用于“help”以外的任何内容?

hax*_*hax 4 python parameter-passing

我正在编写一段代码,必须将主机名作为可选参数传递。还需要使用 -h 选项传递。

用法:

./program.py -h hostname
Run Code Online (Sandbox Code Playgroud)

Argparse 默认使用 -h 来打印帮助。是否有可能以某种方式覆盖它?

C. *_*tra 5

没问题,您所要做的就是传递add_help=FalseArgumentParser构造函数。

import argparse
parser = argparse.ArgumentParser(add_help=False)
Run Code Online (Sandbox Code Playgroud)

然而,如果您仍然想拥有帮助功能,那就没那么容易了。在这种情况下,我建议只调用你的主机参数-H或其他东西。如果你真的想这样做,这是一种方法,但它绝对是一种黑客:

import argparse
parser = argparse.ArgumentParser(add_help=False)
parser._add_action(argparse._HelpAction(
    option_strings=['-H', '--help'],
    help='Show this help message and exit'
))
Run Code Online (Sandbox Code Playgroud)

编辑:感谢@chepner 指出了添加帮助功能的更清晰的方法:

parser.add_argument('-H', '--help', action='help',
    help='show this help message and exit')
Run Code Online (Sandbox Code Playgroud)