简体   繁体   English

python 2.7-argparse:可选参数的参数

[英]python 2.7 - argparse: parameters to optional arguments

I have the following Code Snippet. 我有以下代码片段。

parser = argparse.ArgumentParser()
parser.set_defaults(func=lambda x: parser.print_usage())

parser.add_argument('-o', '--overview', help="print overview",
                    action='store_true')

parser.add_argument('-a', '--add', help='add sudo item', nargs='*',
                    dest="ldap_attrs")
parser.add_argument('dn, object_class, attributes', nargs='*')

parser.add_argument('-d', '--delete', help='delete sudo item', dest='action',
                    action='store_const', const=deleteItem)
parsed_args = parser.parse_args()

It prints out the following: 它打印出以下内容:

usage: sudoadm.py [-h] [-o] [-a [LDAP_ATTRS [LDAP_ATTRS ...]]] [-d]

                  [dn, object_class, attributes [dn, object_class, attributes ...]]

positional arguments:
  dn, object_class, attributes

optional arguments:
  -h, --help            show this help message and exit
  -o, --overview        print overview
  -a [LDAP_ATTRS [LDAP_ATTRS ...]], --add [LDAP_ATTRS [LDAP_ATTRS ...]]
                        add sudo item
  -d, --delete          delete sudo item

I want the positional Arguments as Input Parametes to the -a Argument (eg: -a dn, object_class, attributes), and if possible the positional Paramters printed in the help message instead of LDAP_ATTRS ( eg: -a [dn, object_class, attributes])? 我希望将位置参数作为-a参数的输入参数(例如:-a dn,object_class,attributes),并在可能的情况下,将位置参数作为帮助信息而不是LDAP_ATTRS打印(例如:-a [dn,object_class,属性])?

When defining a positional, the call is: 定义位置时,调用为:

parser.add_argument(dest, nargs='*', help='...', ...)

That is, the one non-keyword argument is the dest , the name of the attribute in args . 也就是说,一个非关键字参数是dest ,即args属性的名称。 That's what the help is showing. 这就是帮助所显示的内容。

A positional does not define the arguments of an optional. 位置不定义可选参数。 The add_argument statements are separate. add_argument语句是单独的。 Omit this add_argument if you aren't defining a positional Action. 如果您未定义位置操作,请忽略此add_argument

In: 在:

parser.add_argument('-a', '--add', help='add sudo item', nargs='*',
                dest="ldap_attrs")

dest specifies the attribute name in args , eg args.ldap_attrs . destargs指定属性名称,例如args.ldap_attrs Without it the attribute would be args.add (the first long flag). 没有它,该属性将是args.add (第一个long标志)。 And the usage would be 用法是

[-a [ADD [ADD ...]]]

I suspect you want to use metavar 我怀疑你想使用metavar

parser.add_argument('-a', '--add', help='add sudo item', nargs='*',
                dest="ldap_attrs", metavar=('dn', 'class'))

With a '*', it only accepts 2 metavar strings. 如果为'*',则仅接受2个metavar字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM