Python command line generator

Is there a command line generator in python? I mean something similar to argparse, but have the opposite functionality. argparse allows you to define various arguments and then parse a given command line in the values โ€‹โ€‹of these arguments. I need something that allows you to define various arguments, such as argparse, but given the argument argument, pairs of values โ€‹โ€‹will generate a command line.

Example:

    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.
+4
source share
2 answers

There is probably enough information in the file Actionsgenerated by the regular parserdefinition to complete this task.

To take part in your example:

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.

0

, - 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
+2

All Articles