building strings with variable input

Olaf Meyer nomail at nospam.net
Mon Jan 12 16:55:42 CET 2004


Erik Max Francis 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.
> 

I just found out another way ;-) Using the locals() has the disadvantage 
that I cannot use more complex variable parameters (e.g. certain values 
of a dictionary). The following works well:

cmd = (executable + " -start " + startTime + " -end " + endTime +
        " -dir " + options.dir)

Olaf



More information about the Python-list mailing list