Executing python script stored as a string

Ecir Hana ecir.hana at gmail.com
Mon Aug 31 19:29:45 EDT 2009


Hello,

please, how to execute a python script stored as a string? But let me
impose several limitations, so simple "exec" wont work:

- if I understood it correctly defining a function in the string and
exec-ing it created the function in current scope. This is something I
really don't want

- simple exec also blocks the rest of the program

- I also would like the string to be able to use and return some parts
of the caller

So to give an example what I try to achieve:

result = []
def up(s):
  result.append(s.upper())

code = '''
up("abc")
print 'hello'
i = i + 3
def x(s):
  up(s)
x('def')
print i
'''

somehow_execute(code)

Couple of points:

- the script in string should behave just like any other ordinary
python script executed in separate process, except it should also know
about a function caller "up". Nothing else. (I read that something
similar is possible while embedding python into your C project - that
you could invoke the VM and provide some default "imports")

- if the other script runs in separate process how should it call the
remote function? And how to pass its arguments? I really hope I don't
have to serialize every communication, maybe I should use threading
instead of process? All I want is that running it wont block the
caller and that it cannot modify callers code/variables/scope (apart
from calling the predefined callers' functions). Or maybe even better,
let it block the caller but provide a way to stop its execution?

- how to know that the script finished? I was thinking about atexit()
- could it work here?

Think of it as a text editor with a special ability to execute its
content, while providing access of some of its functionality to the
script.

The reason I *think* I cannot just simple import the "editor" module
into the script is that the"editor" is GUI application and script
should have access to just this instance of editor.

Anyway, I hope I was not too confusing. Thanks for any help!



More information about the Python-list mailing list