Skip to main content
 首页 » 编程设计

python之如何使用 Python 的 argparse 设置命令行参数 -h

2025年05月04日15soundcode

我有以下 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