Executing a string as python code

Stephen Boulet stephen at theboulets.net
Wed Oct 24 08:01:24 EDT 2001


Yes, but this is no cgi script. It's in my program, which, after all, also 
executes python code.

If I write:

<<
command = ''
for i in range(100):
    command = command + 'list%d = []\n' % i

exec(command)

>>

That's no less secure than typing them out by hand, right?

-- Stephen

Richard Jones wrote:

> On Wednesday 24 October 2001 13:30, Stephen Boulet wrote:
>> Can someone tell me how to execute an arbitrary string as python code?
>>
>> I'm trying to make a bunch of lists named list00, list01, ..., to list99
>> (I don't want to make a single list of lists, since list00 is actually
>> already a list of lists), and I thought doing this as a string would be
>> the easiest way.
>>
>> I guess a dictionary with string keys and list values would be another
>> way (maybe a better way).
> 
> Pretty much any time you're considering "execute an arbitrary string as
> python code", you're doing things the (hard|insecure) way.
> 
> Investigate using a dictionary.
> 
> 
>     Richard




More information about the Python-list mailing list