exec and traceback

Chris Angelico rosuav at gmail.com
Mon Jan 22 08:38:11 EST 2018


On Mon, Jan 22, 2018 at 7:22 PM,  <ken.py at gameofy.com> wrote:
>
>
> I'm using exec() to run a (multi-line) string of python code. If an
> exception occurs, I get a traceback containing a stack frame for the string.
> I've labeled the code object with a "file name" so I can identify it easily,
> and when I debug, I find that I can interact with the context of that stack
> frame, which is pretty handy.
>
> What I would like to also be able to do is make the code string visible to
> the debugger so I can look at and step through the code in the string as if
> it were from a python file.

If you're interacting with a stack frame, you should have access to
its locals and globals, right? Worst case, all you need is this:

_exec = exec
def exec(source):
    return _exec(source)

There, now you guarantee that you have a stack frame with the source
code visible in it. If you control the code which calls exec, you
could just do the same thing there:

source = ...
exec(source)

Either way, it should be accessible from the frame's f_locals.

> Lest this topic forks into a security discussion, I'll just add that for my
> purposes the data source is trusted. If you really want to talk about the
> security of using exec and eval, fine, but start another thread (BTW, I've
> written a simple secure eval())....

That would indeed be another thread, but I can guarantee you that your
"simple secure eval" is either *extremely* simple (with restricted
data types and operations) or not secure.

ChrisA



More information about the Python-list mailing list