run a string as code?

py_genetic conor.robinson at gmail.com
Mon Jul 17 19:26:54 EDT 2006


mtbeedee at gmail.com wrote:
> py_genetic wrote:
> > How can you make python interpret a string (of py code) as code.  For
> > example if you want a py program to modify itself as it runs.  I know
> > this is an advantage of interpreted languages, how is this done in
> > python.  Thanks.
>
> This might do it...
>
> >>> print eval.__doc__
> eval(source[, globals[, locals]]) -> value
>
> Evaluate the source in the context of globals and locals.
> The source may be a string representing a Python expression
> or a code object as returned by compile().
> The globals must be a dictionary and locals can be any mappping,
> defaulting to the current globals and locals.
> If only globals is given, locals defaults to it.

For example each time this line is interpreted I would like to use the
new value of the state var which is a global var.  How can I force
state to be identified and used in this string.

r_table = h5file.root.state_raw_records.neg_records

r_table = eval("h5file.root.state_raw_records.neg_records") ??
r_table = h5file.root.eval("state")_raw_records.neg_records ?? eval is
not a part of root

dont think either of these is very logical? Any ideas?  Possibly the
parser mod?




More information about the Python-list mailing list