简体   繁体   English

argparse用于未知数量的参数和未知名称

[英]argparse for unknown number of arguments and unknown names

I'd like to fetch all parameters passed to sys.argv that have the format 我想获取传递给sys.argv所有格式的参数
someprogram.py --someparameter 23 -p 42 -anotherparam somevalue . someprogram.py --someparameter 23 -p 42 -anotherparam somevalue

Result I'm looking for is a namespace containing all the variables, already parsed. 结果我正在寻找的是一个包含所有已解析变量的名称空间。

To my understanding, argparse is expecting the user to define what are the parameters he is expecting. 据我了解,argparse期望用户定义他期望的参数。

Any way to do that with argparse ? 用argparse可以做到吗? Thanks ! 谢谢 !

If you know that the parameters will always be given in the format --name value or -name value you can do it easily 如果您知道参数将始终以--name value-name value的格式给出,则可以轻松实现

class ArgHolder(object):
    pass

name = None
for x in sys.argv[1:]:
    if name:
        setattr(ArgHolder, curname, x)
        name = None

    elif x.startswith('-'):
        name = x.lstrip('-')

Now you will have collected all arguments in the class ArgHolder which is a namespace. 现在,您将已在ArgHolder的类中收集了所有参数。 You may also collect the values in an instance of ArgHolder 您也可以在ArgHolder实例中收集值

Using Click we can build such a command: 使用Click,我们可以构建这样的命令:

import click

@click.command(help="Your description here")
@click.option("--someparameter", type=int, help="Description of someparameter")
@click.option("--p", type=int, help="Description of p")
@click.option("--anotherparam", type=str, help="Description of anotherparam")
def command(someparameter, p, anotherparam):
    pass


if __name__ == '__main__':
    command()

And you will have a help option automatically: 您将自动获得一个帮助选项:

$ python command.py --help
Usage: command.py [OPTIONS]

  Your description here.

Options:
  --someparameter INTEGER  Description of someparameter.
  ...
  --help           Show this message and exit.

If you need to get all unknown arguments, you can get them from a context in such way: 如果需要获取所有未知参数,则可以通过以下方式从上下文中获取它们:

@click.command(context_settings=dict(
     ignore_unknown_options=True,
     allow_extra_args=True,
 ), add_help_option=False)
@click.pass_context
def command(ctx):
    click.echo(ctx.args)

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

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