Executing python script stored as a string

Ecir Hana ecir.hana at gmail.com
Tue Sep 1 10:34:33 CEST 2009

On Sep 1, 5:31 am, Steven D'Aprano
<ste... at REMOVE.THIS.cybersource.com.au> wrote:
> You can pass in a global and local namespaces to exec as arguments:
> >>> x = 4
> >>> ns = {'x': 4}
> >>> exec "x += 1" in ns
> >>> x
> 4
> >>> ns['x']
> 5
> See the docs for details.

Thanks! This is very useful!

> You can copy the parts of the current scope into the namespace you pass
> to exec, then later copy the revised values out again.
> But are you sure you really want to take this approach? exec is up to ten
> times slower than just executing the code directly. And if the string is
> coming from an untrusted source, it is a *huge* security risk.

I don't know if I should use exec. I don't really mind that it's slow
(btw., why is it so?). But I don't quite understand why is it security
risk. How is it different to run:
exec 'format(your_hdd)'
/bin/python format.py

> As far as I know, you can't kill threads, you can only ask them to kill
> themselves.

Also, I'm not sure if I follow. What does this mean? If a thread runs:

while True:

it is not possible to kill it from another thread? (Bacause it doesn't
check whether some other thread asks to stop it..?)

> Something like this?

Well, something more like:

data = [1, 2, 3]
map(lambda x: x * 2, data)
display_data_in_editor_viewport(data) #this renders into part of main
editor window (may take some time)

> If so, I think you are making this much too complicated for such a simple
> use-case. Just publish an API which the script can use, and have the main
> text editor application specify a "script" namespace containing only that
> API. That could be a module:
> >>> import math  # pretend this is your API shared module
> >>> exec "myvalue = 42" in math.__dict__
> >>> math.myvalue
> 42
> Then execute the text using exec, but don't bother about putting it into
> a thread or subprocess. That just makes it harder to implement, and you
> have to worry about concurrency issues.

Ok, I could try exec, thanks for the explanation. But what about those
security concerns you mentioned above?

Thanks a lot, very informative!

More information about the Python-list mailing list