exec and traceback

Ned Batchelder ned at nedbatchelder.com
Thu Jan 25 06:42:34 EST 2018


On 1/22/18 3:22 AM, 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.
>
> 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())....
>

I haven't tried this, but what if you write the string to a temporary 
file, and then claim that the code came from that file? Code objects are 
immutable, so you'll need to recompile a new code object, but then you 
can poke that object into the frame (I think?).  It will be fiddly, and 
may not work at all, as is typical with hacking at this level of the 
interpreter.

I'm still interested in your simple secure eval if you have the time to 
tell us about it.

--Ned.



More information about the Python-list mailing list