如何使用 Python 的 argparse 设置命令行参数 -h?
How can I have a command-line argument -h with Python's argparse?
我有以下 python:
import argparse
parser = argparse.ArgumentParser()
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('-h', '--host_name', required=True, help="Host IP address")
args = parser.parse_args()
这会产生以下错误:
argparse.ArgumentError: argument -h/--help: conflicting option string(s): -h
除 -h
外,每个字母都可以正常工作。它似乎是为 --help 保留的。我怎样才能让它不被自动保留-h
?
ArgumentParser
采用可选参数 add_help
,您可以将其设置为 False
.
在 add_help
的文档中:
Occasionally, it may be useful to disable the addition of this help option. This can be achieved by passing False
as the add_help=
argument to ArgumentParser
:
>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
>>> parser.add_argument('--foo', help='foo help')
>>> parser.print_help()
usage: PROG [--foo FOO]
optional arguments:
--foo FOO foo help
我有以下 python:
import argparse
parser = argparse.ArgumentParser()
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('-h', '--host_name', required=True, help="Host IP address")
args = parser.parse_args()
这会产生以下错误:
argparse.ArgumentError: argument -h/--help: conflicting option string(s): -h
除 -h
外,每个字母都可以正常工作。它似乎是为 --help 保留的。我怎样才能让它不被自动保留-h
?
ArgumentParser
采用可选参数 add_help
,您可以将其设置为 False
.
在 add_help
的文档中:
Occasionally, it may be useful to disable the addition of this help option. This can be achieved by passing
False
as theadd_help=
argument toArgumentParser
:>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) >>> parser.add_argument('--foo', help='foo help') >>> parser.print_help() usage: PROG [--foo FOO] optional arguments: --foo FOO foo help