A question about a list and subprocess.check_call()

Peter Otten __peter__ at web.de
Mon Feb 16 10:19:56 EST 2015


David Aldrich wrote:

> Hi
> 
> I wonder if someone could help me with this problem please.  I am writing
> a Python script that builds and tests a C++ program on Linux.  The build
> options depend on the test, so I have encapsulated the 'make' call in a
> Python function:
> 
> def build(build_options=''):
>         if len(build_options):
>             subprocess.check_call(['make',build_options])
>         else:
>             subprocess.check_call('make')
> 
> This works fine if I call:
> 
> build()
> or
> build('flagA=true')
> 
> The latter gives:
> 
> make flagA=true
> 
> which is correct.
> 
> However, I now want to call make with two flags:
> 
> make flagA=true flagB=true
> 
> I tried calling:
> 
> build('flagA=true flagB=true')
> 
> which did indeed result in:
> 
> make flagA=true flagB=true
> 
> but 'make' ignored the second option. So I think that the list that was
> passed to subprocess.check_call() was incorrect.

That's because you effectively call

subprocess.check_call(["make", "flagA=true flabB=true"])

i. e. you are providing a single parameter "flagA=true flabB=true" instead 
of two separate "flagA=true" and "flabB=true"

> In summary, I want to pass a list to build(), which by default should be
> empty, and pass that list on to subprocess.check_call() with 'make' as the
> first element of the list.
> 
> Any ideas please?

The straightforward approach is to pass a list or tuple:

def build(build_options=()):
    subprocess_check_call(("make",) + build_options)

build(("flagA=true", "flagB=true"))

Allowing separate arguments may be more convenient to use:

def build(*build_options):
    subprocess.check_call(("make",) + build_options)

build("flagA=true", "flagB=true")

Or, if the order of flags doesn't matter:

def build(*args, **kw):
    subprocess.check_call(("make",) + args + 
        tuple("{}={}".format(*p) for p in kw.items()))

build(flagA="true", flagB="true")





More information about the Python-list mailing list