Calling Python Code Snippets within Python Application

Robin Munn rmunn at pobox.com
Mon Apr 14 11:03:07 EDT 2003


Marc Floessel <gildemere at hotmail.com> wrote:
> This is very likely a newbie question, but I'd still appreciate a
> pointer. I need to call Python Code snippets (saved in a file/database
> etc) within my main Python Application. I would like to do the
> following things:
> 
> - Code Snippet should not have access to or knowledge of Main
> Application variables and methods - ie. each code snippet has its own
> private scope
> - main application exposes a number of specific methods and variables
> ("environment") to the snippet that it can use
> - a way for the code snippet to return some variables (ie. a success
> bool) - possibly using (re-importing back from the snippet) the
> variables exposed by the main application
> 
> In which direction should I look?

Look at the eval() or execfile() built-ins:

    http://www.python.org/doc/current/lib/built-in-funcs.html

Note that eval() evaluates an expression -- if you want to use eval() to
run chunks of Python code, you might have to wrap those chunks in a
function and eval() the result of calling that function. execfile() will
work if the code you want is in a file; if it's in a database, you might
have to write it to a temporary file and then execfile() that temporary
file.

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838




More information about the Python-list mailing list