python中的通用命令行生成器

时间:2015-07-09 19:44:23

标签: python argparse

python中是否有通用的命令行生成器?我的意思是像argparse,但具有相反的功能。 argparse允许您定义各种参数,然后将给定的命令行字符串解析为这些参数的值。我需要一些东西,让你定义各种参数,如argparse,但给定一个参数的dict,值对将生成一个命令行字符串。

示例:

    gencmdline = CmdlineGenerator()
    gencmdline.add_argument('-f', '--foo')
    gencmdline.add_argument('bar')
    gencmdline.add_argument('phi')
    gencmdline.gen_cmdline(phi='hello', bar=1, foo=2) returns: 
    "1 hello -f 2"
    gencmdline.gen_cmdline(phi='hello', bar=1) returns:
    "1 hello"
    gencmdline.gen_cmdline(phi='hello', foo=2) raise exception because positional argument bar is not specified.

2 个答案:

答案 0 :(得分:2)

我假设你想要使用类似call之类的东西,并传递命令一些关键字。

from subprocess import call

def get_call_array(command=command,**kwargs):
    callarray = [command]
    for k, v in self.kwargs.items():
        callarray.append("--" + k)
        if v:
            callarray.append(str(v))
    return callarray

call(get_call_array("my_prog",height=5,width=10,trials=100,verbose=None))

#calls:   my_prog --height 5 --width 10 --trials 100  --verbose

当然,如果您有所有参数的字典,那就更容易了:

def get_call_array_from_dict(command,options_dict):
    callarray=[command]
    for k,v in options_dict.items():
        callarray.append("--" + str(k))
        if v:
            callarray.append(str(v))
    return callarray

答案 1 :(得分:0)

正常Actions定义生成的parser中可能有足够的信息来完成这项工作。

参加你的例子:

In [122]: parser=argparse.ArgumentParser()
In [123]: arglist = []
In [124]: arg1 = parser.add_argument('-f','--foo')    
In [126]: arglist.append(arg1)
In [128]: arg2=parser.add_argument('bar')
In [129]: arglist.append(arg2)
In [131]: arg3=parser.add_argument('phi')
In [132]: arglist.append(arg3)

In [133]: arglist
Out[133]: 
[_StoreAction(option_strings=['-f', '--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None),

 _StoreAction(option_strings=[], dest='bar', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None),

 _StoreAction(option_strings=[], dest='phi', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)]

add_argument创建一个Action对象(子类实际上基于action类型),其属性是默认值或您使用参数指定的属性。

在这个例子中,我将它们作为变量arg1和列表元素收集。此repr中未显示其他属性。您可以在交互式翻译中探索这些内容。

从您的词典dict(phi='hello', bar=1, foo=2)和此列表中,您可以推断出dest='foo'的参数有一个选项字符串(-f--foo),其他所有内容都是默认值(nargs=None是默认的1参数)。 dest='bar'是空的option_strings。您必须小心并注意bar发生在phi之前。

parser._actions

是相同的操作列表,添加了-h

相关问题