Python-将参数传递给Argparse的不同方法 [英] Python - Pass Arguments to Different Methods from Argparse

查看:269
本文介绍了Python-将参数传递给Argparse的不同方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个相对简单的Python脚本,该脚本支持几个不同的命令.不同的命令支持不同的选项,我希望能够将argparse解析的选项传递给指定命令的正确方法.

I'm writing a relatively simple Python script which supports a couple of different commands. The different commands support different options and I want to be able to pass the options parsed by argparse to the correct method for the specified command.

用法字符串如下所示:

usage: script.py [-h]

            {a, b, c}
            ...
script.py: error: too few arguments

我可以轻松地调用适当的方法:

I can easily call the appropriate method:

def a():
    ...

def b():
    ...

def c():
    ...

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.set_defaults(method = a)
    ...

    arguments = parser.parse_args()
    arguments.method()

但是,我必须将参数传递给这些方法,并且它们都接受不同的参数集.

However, I have to pass arguments to these methods and they all accept different sets of arguments.

目前,我只传递了argparse返回的Namespace对象,如下所示:

Currently, I just pass the Namespace object returned by argparse, like so:

 def a(arguments):
     arg1 = getattr(arguments, 'arg1', None)
     ...

这似乎有些尴尬,并且使这些方法难以重用,因为我必须将参数作为dict或名称空间而不是通常的参数来传递.

This seems a little awkward, and makes the methods a little harder to reuse as I have to pass arguments as a dict or namespace rather than as usual parameters.

我想以某种方式定义带有参数的方法(就像普通函数一样),并且仍然能够在传递适当的参数的同时动态地调用它们.像这样:

I would like someway of defining the methods with parameters (as you would a normal function) and still be able to call them dynamically while passing appropriate parameters. Like so:

def a(arg1, arg2):
    ...

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.set_defaults(method = a)
    ...

    arguments = parser.parse_args()
    arguments.method() # <<<< Arguments passed here somehow

有什么想法吗?

推荐答案

我找到了一个很好的解决方案:

I found quite a nice solution:

import argparse

def a(arg1, arg2, **kwargs):
    print arg1
    print arg2

if __name__ == "__main__":
        parser = argparse.ArgumentParser()
        parser.set_defaults(method = a)
        parser.add_argument('arg1', type = str)
        parser.add_argument('arg2', type = str)

        arguments = parser.parse_args()
        arguments.method(**vars(arguments))

如果方法的参数与argparse使用的参数名称发生冲突,当然会有一个小问题,尽管我认为这比传递名称空间对象和使用getattr更可取.

Of course there's a minor problem if the arguments of the method clash with the names of the arguments argparse uses, though I think this is preferable to passing the Namespace object around and using getattr.

这篇关于Python-将参数传递给Argparse的不同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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