本文介绍了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设置中设置:

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-一次访问多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 04:22
查看更多