building strings with variable input

David M. Cooke cookedm+news at
Mon Jan 12 16:27:38 CET 2004

At some point, Erik Max Francis <max at> wrote:

> Olaf Meyer wrote:
>> Especially if you have a lot of variable input it makes it hard to
>> match
>> the variables to the proper fields. From other scripting languanges
>> I'm
>> used to something like:
>>   $cmd = "$executable -start $startTime -end $endTime -dir $directory"
>> This makes it very easy to see how the string is actually built. You
>> dont't have to worry where which variables go.
>> Is there a similar way to do this in python?
> Sure:
> cmd = "%(executable)s -start %(startTime)s -end %(endTime)s -dir
> %(directory)s" % locals()
> There are also more expansive solutions such as YAPTU or EmPy.
> Note, however, that what you are trying to do (presuming you're passing
> this to os.system or something similar) is potentially a serious
> security risk.  If the values of the strings you are constructing the
> command line are not fully trustworthy, they can be easily manipulated
> to make your program execute arbitrary shell commands.

In which case he's probably better off with his original format (almost):

cmd = '"$executable" -start "$startTime" -end "$endTime" -dir "$directory"'
os.environ['executable'] = 'blah'
os.environ['startTime'] = '12'
os.environ['endTime'] = '18'
os.environ['directory'] = './'

This way, the shell handles all the quoting. You can do
del os.environ['executable']
afterwards to clean up. I got this technique from

For the quoting, compare:
>>> os.environ['string'] = "`uname` $TERM"
>>> os.system('echo "$string"')
`uname` $PATH
(this is what we want: don't run arbitrary commands or expand
environment variables given in a user string)

>>> string = "`uname` $TERM"
>>> os.system('echo "%s"' % string)
Linux xterm
(whoops, security leak)

|David M. Cooke

More information about the Python-list mailing list