sandboxing/running python code line by line

后端 未结 7 1330
遥遥无期
遥遥无期 2020-12-14 03:50

I\'d love to be able to do something like these two are doing:

Inventing on principle @18:20 , Live ClojureScript Game Editor

If you don\'t wanna check the v

7条回答
  •  再見小時候
    2020-12-14 04:19

    Update: After my initial success with this technique, I switched to using the ast module as described in my other answer.

    sys.settrace() seems to work really well. I took the hacks question you mentioned and Andrew Dalke's article and got this simple example working.

    import sys
    
    def dump_frame(frame, event, arg):
        print '%d: %s' % (frame.f_lineno, event)
        for k, v in frame.f_locals.iteritems():
            print '    %s = %r' % (k, v)
        return dump_frame
    
    def main():
        c = 0
        for i in range(3):
            c += i
    
        print 'final c = %r' % c
    
    sys.settrace(dump_frame)
    
    main()
    

    I had to solve two problems to get this working.

    1. The trace function has to return itself or another trace function if you want to continue tracing.
    2. Tracing only seems to begin after the first function call. I originally didn't have the main method, and just went directly into a loop.

    Here's the output:

    9: call
    10: line
    11: line
        c = 0
    12: line
        i = 0
        c = 0
    11: line
        i = 0
        c = 0
    12: line
        i = 1
        c = 0
    11: line
        i = 1
        c = 1
    12: line
        i = 2
        c = 1
    11: line
        i = 2
        c = 3
    14: line
        i = 2
        c = 3
    final c = 3
    14: return
        i = 2
        c = 3
    38: call
        item = 
        selfref = 
    38: call
        item = 
        selfref = 
    

提交回复
热议问题