Argparse - 一次访问多个参数 [英] Argparse - accessing multiple arguments at once

查看:20
本文介绍了Argparse - 一次访问多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序使用数据库,所以当添加一个新元素(从命令行)时,我想检查这个元素是否已经在数据库中,我用 add_argument 的type"参数做了什么:

my application uses a database, so when adding a new element (from command line) I want to check if this one is already in the database, what I do with the "type" parameter of add_argument:

def check_uniq(project_name):
    if Project.exists(project_name):
        raise argparse.ArgumentTypeError(
    return project_name

这工作得很好,但是为了让最终用户更容易思考,我想在我的参数中添加一个 --force 选项,以便在添加和之前测试并删除此变量在这种情况下,请注意提出论点.如何在 check_uniq 中访问 --force 选项?

this is working just fine, however to make think easier to the final user I'd like to add a --force option to my arguments so this variable is tested and delete before to add and in this case do note raise the argument. How can I access within the check_uniq to the --force option ?

推荐答案

测试该选项是否设置在同一个if stamement:

Test if the option is set in the same if stamement:

def check_uniq(project_name, options):
    if Project.exists(project_name) and not options.force:
        raise argparse.ArgumentTypeError('Project already exists')
    return project_name

其中 options 接受 parser.parse_args() 返回的 Namespace 实例.

where options takes the Namespace instance returned by parser.parse_args().

不幸的是,在解析完所有参数之前,您无法验证这一点,您不能将此函数用作type参数,因为--force 选项可以在命令行的任何位置指定,在指定项目名称的选项之前或之后.

Unfortunately, you cannot verify this until all arguments have been parsed, you cannot use this function as a type parameter, because the --force option can be specified anywhere on the command line, before or after the option that specifies your project name.

如果您要求 --force 在命令行中的任何项目之前列出,您可以使用自定义action 代替;一个自定义操作被传递给 namespace 对象作为解析到目前为止:

If you require that --force is listed before any projects on your command line, you could use a custom action instead; a custom action is passed the namespace object as parsed so far:

class UniqueProjectAction(argparse.Action):
    def __call__(self, parser, namespace, value, option_string=None):
        if Project.exists(value) and not namespace.force:
            raise argparse.ArgumentTypeError('Project already exists')
        setattr(namespace, self.dest, values)

这篇关于Argparse - 一次访问多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆