Jason Macgowan
Jason Macgowan

Reputation: 524

Additional processing of arugments for a function in Python

In writing a small library, I've found the need to sanitize input on all of the arguments of a function, shown below:

import subprocess
import pipes

def copy(src, dst, id_file='/path/to/key'):
    src = pipes.quote(src)
    dest = pipes.quote(dest)
    id_file = pipes.quote(id_file)

    subprocess.check_output('scp -r -i %s %s %s' % (id_file, src, dest))

Instead of explicitly running each argument through pipes.quote(), how could I do this more elegantly, and for any number of arguments (including *args and **kwargs, if present)?

Upvotes: 0

Views: 31

Answers (1)

mgilson
mgilson

Reputation: 309929

Most subprocess functions accept a list of arguments:

subprocess.check_output(['scp', '-r', '-i', id_file, src, dest])

Quoting is no longer necessary.

This generalizes nicely to *args:

def foo(*args, **kwargs):
    call_args = ['scp', '-r', '-i']
    call_args.extend(args)
    call_args.extend(arg for item in kwargs.items() for arg in item)
    subprocess.check_output(call_args)

Of course, with kwargs, you never know what order they'll end up in the resulting call . . .

Upvotes: 1

Related Questions