问题:使用Python argparse创建隐藏参数

是否可以在Python 的用法或帮助(script.py --help)中不显示参数的情况下将其添加到python中?

Is it possible to add an Argument to an python without it showing up in the usage or help (script.py --help)?


回答 0

是的,您可以将help选项设置add_argumentargparse.SUPPRESS。这是argparse文档中的示例:

>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('--foo', help=argparse.SUPPRESS)
>>> parser.print_help()
usage: frobble [-h]

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

Yes, you can set the help option to add_argument to argparse.SUPPRESS. Here’s an example from the argparse documentation:

>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('--foo', help=argparse.SUPPRESS)
>>> parser.print_help()
usage: frobble [-h]

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

回答 1

我通过添加启用隐藏选项的选项来做到这一点,并通过查看来获取它sysv.args

如果执行此操作,sys.argv则如果您假设选项是-s启用隐藏选项,则必须将您从中选择的特殊参数直接包含在解析列表中。

parser.add_argument('-a', '-axis',
                    dest="axis", action="store_true", default=False,
                    help="Rotate the earth")
if "-s" in sys.argv or "-secret" in sys.argv:
    parser.add_argument('-s', '-secret',
                        dest="secret", action="store_true", default=False,
                        help="Enable secret options")
    parser.add_argument('-d', '-drill',
                        dest="drill", action="store_true", default=False,
                        help="drill baby, drill")

I do it by adding an option to enable the hidden ones, and grab that by looking at sysv.args.

If you do this, you have to include the special arg you pick out of sys.argv directly in the parse list if you Assume the option is -s to enable hidden options.

parser.add_argument('-a', '-axis',
                    dest="axis", action="store_true", default=False,
                    help="Rotate the earth")
if "-s" in sys.argv or "-secret" in sys.argv:
    parser.add_argument('-s', '-secret',
                        dest="secret", action="store_true", default=False,
                        help="Enable secret options")
    parser.add_argument('-d', '-drill',
                        dest="drill", action="store_true", default=False,
                        help="drill baby, drill")

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。