How can I start the python console within a program (for easy debugging)?

前端 未结 6 1645
说谎
说谎 2021-02-10 03:52

After years of research programming in Matlab, I miss the way I could pause a program mid-execution and inspect the variables, do plotting, save/modify data, etc. via the intera

6条回答
  •  渐次进展
    2021-02-10 04:35

    The excellent solution I found was to use the 'code' module. I can now call 'DebugKeyboard()' from anywhere in my code and the interpreter prompt will pop-up, allowing me to examine variables and run code. CTRL-D will continue the program.

    import code
    import sys    
    
    def DebugKeyboard(banner="Debugger started (CTRL-D to quit)"):
    
        # use exception trick to pick up the current frame
        try:
            raise None
        except:
            frame = sys.exc_info()[2].tb_frame.f_back
    
        # evaluate commands in current namespace
        namespace = frame.f_globals.copy()
        namespace.update(frame.f_locals)
    
        print "START DEBUG"
        code.interact(banner=banner, local=namespace)
        print "END DEBUG"
    

提交回复
热议问题