Finger twist
Finger twist

Reputation: 3786

generating subprocess.call arguments from a list

I am using the subprocess module to execute a command line software with arguments but I am running into a bit of trouble when it comes to feeding it a list of arguments .

Here is what I am doing :

subprocess.call([rv,"[",rv_args[0],rv_args[1],"]",])

This works fine and len(rv_args) == 2 , now I would like to generate this :

if len(rv_args) == 4 :
    subprocess.call([rv,"[",rv_args[0],rv_args[1],"]","[",rv_args[2],rv_args[3],"]",])

then

if len(rv_args) == 6 :
    return subprocess.call([rv,"[",rv_args[0],rv_args[1],"]","[",rv_args[2],rv_args[3],"]","[",rv_args[4],rv_args[5],"]"])

etc .. etc ..

Of course I don't want to hard code it, but generate it on the fly, what you be the best way ?

cheers,

Upvotes: 0

Views: 131

Answers (1)

Andrew Alcock
Andrew Alcock

Reputation: 19651

Here's one way:

rv = "command"
rv_args = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


def get_arguments(rv, rv_args):
    arguments = [rv]
    for i in xrange(0, len(rv_args), 2):
        arguments += ["["] + rv_args[i:i+2] + ["]"]

    return arguments

print get_arguments(rv, rv_args)

returns:

['command', '[', 1, 2, ']', '[', 3, 4, ']', '[', 5, 6, ']', '[', 7, 8, ']', '[', 9, 10, ']']

Upvotes: 1

Related Questions