Executing a command from within python using the subprocess module

John Posner jjposner at optimum.net
Mon Feb 15 10:59:05 EST 2010


On 2/15/2010 7:35 AM, R (Chandra) Chandrasekhar wrote:
> Dear Folks,
>
> I want to execute a command from within python using the subprocess module.
>
> Coming from a Perl background, I thought I could use variable
> interpolation in strings, but found that this is neither supported

Yes, it is: see the use of string.Template below.

> ... nor
> the Python way.

That right -- it isn't the Python way. Python offers two basic 
alternatives. Alf already presented the use of the "new" format() method 
of string objects. I think "traditional" Python string formatting might 
be what you want in this case:

   colors = ['#abcdef', '#456789']
   format_string = "convert -size 5x30 gradient:%s-%s /tmp/image.png"
   cmd_string = format_string % tuple(colors)

... or better, by making *colors* a tuple instead of a list ...

   colors = ('#abcdef', '#456789')
   format_string = "convert -size 5x30 gradient:%s-%s /tmp/image.png"
   cmd_string = format_string % colors

As Peter demonstrated, you need to use split() on *cmd_string* when you 
send the command to subprocess.call().

Now if you *really* miss using Perl, try this:

   c1, c2 = ('#abcdef', '#456789')
   template = string.Template(
               "convert -size 5x30 gradient:$c1-$c2 /tmp/image.png")
   cmd_string = template.substitute(locals())

Not worth the trouble, IMHO.

Refs:

http://www.python.org/doc/2.5.2/lib/typesseq-strings.html
http://www.python.org/doc/2.5.2/lib/node40.html

HTH,
John



More information about the Python-list mailing list