How to use the exec statement
Alex Martelli
aleax at aleax.it
Sun Oct 6 16:09:06 EDT 2002
JB wrote:
...
>> can avoid the worst problems: build an artificial
>> namespace (i.e., a suitably prepared dictionary) in which
>> these statements are to execute -- populate it with
>> whatever set of names you think the user will need (module
>> r_exec is also a possibility).
>
> How can I do this?
namespace = {}
# populate dict namespace with whatever you want, e.g.:
import math
namespace.update(math.__dict__)
# etc etc
Now, when it comes time to exec the user-given statement
X,
exec X in namespace
This way the namespace will be the same from one such
statement to the next. If you DON'T want that, e.g.:
new_namespace = namespace.copy()
exec X in new_namespace
Now, if needed, you can examine namespace or new_namespace
for any significant changes (settings/un-settings) that you want
to take into account.
BTW, you wouldn't have to write a parser anyway -- there are
some you can use already in the Python standard libraries, and
others you can download. But exec isn't too bad if [a] Python is
the right language for the user to be using and [b] you use exec
in a well-controlled manner. You'll probably want to have a
try/except around the exec statement, for more precise error
messages than just a program-crash, and if you need to exec
the same statement repeatedly, look into built-in "compile"
(you can compile the statement once, getting a code-object,
then exec the code-object repeatedly).
Alex
More information about the Python-list
mailing list