python - ArgumentParser -h 在 parse_known_args 之后不打印选项

标签 python command-line-arguments argparse

我的脚本包含一长串可选参数,最近我在其中添加了通过文件传递参数的选项。其代码如下:我首先添加 from_file 参数,然后添加 parse_known_args。除了 -h 标志之外,一切正常。调用此标志时的输出仅引用在 parse_known_args 调用之前添加的参数。

问题:如何获得帮助选项来识别 parse_known_args 调用后的所有参数?

# grab values from file_parser or default
def getInitVar(variable, parser, default, varList=False):
    if parser:
        if varList:
            return [o.strip() for o in parser.get('constants',variable).split(",")] if parser.has_option('constants',variable) else default
        else:
            return parser.get('constants',variable) if parser.has_option('constants',variable) else default
    else:
        return default

# first parser for to/from file parameters
parser = argparse.ArgumentParser(
    description='', prefix_chars='-+', formatter_class=argparse.ArgumentDefaultsHelpFormatter)

# Meta variables
group = parser.add_argument_group('Meta Variables', '')
group.add_argument('--to_file', dest='toinitfile', nargs='?', const=DEF_INIT_FILE, default=None,
                  help='write flag values to text file')
group.add_argument('--from_file', type=str, dest='frominitfile', default='',
                   help='reads flag values from file')

args, remaining_argv = parser.parse_known_args()

# create second parser for reading from files
if args.frominitfile:
    conf_parser = SafeConfigParser()
    conf_parser.read(args.frominitfile)
else:
    conf_parser = None

group = parser.add_argument_group('Some Group', 'blah blah')

group.add_argument('-someFlag', dest='somevar', default=getInitVar('corpdb', conf_parser, DEF_VAR),
                    help='Some help.')
....

使用-h标志时的输出:

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

Meta Variables:
--to_file [TOINITFILE]
                    write flag values to text file (default: None)
--from_file FROMINITFILE
                    reads flag values from file (default: )

编辑:在我的代码中添加了一些详细信息(如评论中的建议),说明为什么我调用 parse_known_args:

  1. 我创建解析器并添加两个参数:from_fileto_file
  2. 解析参数。如果存在 from_file,我将创建第二个解析器并读取输入变量。
  3. 继续向解析器添加参数。默认值是我向其传递第二个解析器和默认值的函数。

编辑:终于弄清楚如何做到这一点,在下面发布了答案。

最佳答案

进行了以下更改:

  1. 使用参数 add_help=False 创建了一个 init_parser
  2. init_parser 作为父级传递给 parser:parents=[init_parser]
  3. 将描述参数从 init_parser 移至 parser

这是最终的代码:

init_parser = argparse.ArgumentParser(prefix_chars='-+', formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=False)

# Meta variables
group = init_parser.add_argument_group('Meta Variables', '')
group.add_argument('--to_file', dest='toinitfile', nargs='?', const=DEF_INIT_FILE, default=None, help='write flag values to text file')
group.add_argument('--from_file', type=str, dest='frominitfile', default='', help='reads flag values from file')

args, remaining_argv = init_parser.parse_known_args()

if args.frominitfile:
    conf_parser = SafeConfigParser()
    conf_parser.read(args.frominitfile)
else:
    conf_parser = None

# Inherit options from init_parser
parser = argparse.ArgumentParser(description='Extract and Manage Language Feature Data.', 
    parents=[init_parser])

group = parser.add_argument_group('Some Group', 'blah blah')

group.add_argument('-someFlag', dest='somevar', default=getInitVar('corpdb', conf_parser, DEF_VAR),
                    help='Some help.')
....

输出:

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

Meta Variables:
--to_file [TOINITFILE]
                write flag values to text file (default: None)
--from_file FROMINITFILE
                reads flag values from file (default: )
Some group:
    blah blah blah
--someFlag
...

关于python - ArgumentParser -h 在 parse_known_args 之后不打印选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35799860/

相关文章:

python - Argparse:制作所需的标志

python - SQLFORM 导出重定向到输入表单

python - 艰难地学习 Python,练习 35 : placing a regular expression

python - 在 Python 中使用命令行参数 : Understanding sys. argv

c - 如何将整数作为命令行参数?

python - argparse:使用强制参数的值设置可选参数

Python错误: No module named 'engine'

python - 根据 ID 添加 Pandas 列值

bash - 使用撇号或引号从终端传递命令行参数

python argparse -- 自定义错误信息