Executing a command from within python using the subprocess module

R (Chandra) Chandrasekhar chyavana at gmail.com
Mon Feb 15 16:48:02 CET 2010

Peter Otten wrote:

> import subprocess
> def convert(width=5, height=30, colors=['#abcdef', '#456789'],
>             filename="tmp/image with space in its name.png"):
>     lookup = locals()
>     assert all("\n" not in str(s) for s in lookup.values())
>     subprocess.call("""\
> convert
> -size
> {width}x{height}
> gradient:{colors[0]}-{colors[1]}
> {filename}""".format(**lookup).splitlines())
> convert()
> Peter

Thank you. It works. Now I need to understand why and am able to follow 
what you are doing part of the way:

1. Assign default values in the function definition.

2. Store the variables existing in the local namespace in the list lookup.

3. Assert that there are no newlines in the values in lookup converted 
to strings. (Why? Is this because of splitlines() later on?)

4. Assemble a string (array?) for the subprocess.call argument using the 
  format string syntax (section 8.1.3 et seq. of the Python 
documentation for 2.6.4). Your example works with  default option of 
shell=False for subprocess.call().

5. I am unable to decipher how you got to format(**lookup).splitlines())
especially the **prefix part, although I guess that splitlines() is 
dishing out the arguments one by one from each line in the 
subprocess.call argument.

Any correction of (1) to (4) and an explanation of (5) would be most 

All in all, your code is a magnificent example of wrapping the function 
within python. This is the first time I have seen something like this.

Thank you very much.


More information about the Python-list mailing list