How to detect that Python code is being executed through the debugger?

后端 未结 8 1726
清酒与你
清酒与你 2020-12-24 12:20

Is there a simple way to detect, within Python code, that this code is being executed through the Python debugger?

I have a small Python application that uses Java c

相关标签:
8条回答
  • 2020-12-24 12:53

    If you're using Pydev, you can detect it in such way:

    import sys
    if 'pydevd' in sys.modules: 
        print "Debugger"
    else:
        print "commandline"
    
    0 讨论(0)
  • 2020-12-24 12:57

    Another way to do it hinges on how your python interpreter is started. It requires you start Python using -O for production and with no -O for debugging. So it does require an external discipline that might be hard to maintain .. but then again it might fit your processes perfectly.

    From the python docs (see "Built-in Constants" here or here):

    __debug__
    This constant is true if Python was not started with an -O option.
    

    Usage would be something like:

    if __debug__:
        print 'Python started without optimization'
    
    0 讨论(0)
  • 2020-12-24 13:00

    A solution working with Python 2.4 (it should work with any version superior to 2.1) and Pydev:

    import inspect
    
    def isdebugging():
      for frame in inspect.stack():
        if frame[1].endswith("pydevd.py"):
          return True
      return False
    

    The same should work with pdb by simply replacing pydevd.py with pdb.py. As do3cc suggested, it tries to find the debugger within the stack of the caller.

    Useful links:

    • The Python Debugger
    • The interpreter stack
    0 讨论(0)
  • 2020-12-24 13:03

    From taking a quick look at the pdb docs and source code, it doesn't look like there is a built in way to do this. I suggest that you set an environment variable that indicates debugging is in progress and have your application respond to that.

    $ USING_PDB=1 pdb yourprog.py
    

    Then in yourprog.py:

    import os
    if os.environ.get('USING_PDB'):
        # debugging actions
        pass
    
    0 讨论(0)
  • 2020-12-24 13:08

    I found a cleaner way to do it,

    Just add the following line in your manage.py

    #!/usr/bin/env python
    import os
    import sys
    
    if __debug__:
        sys.path.append('/path/to/views.py')
    
    
    if __name__ == "__main__":
        ....
    

    Then it would automatically add it when you are debugging.

    0 讨论(0)
  • 2020-12-24 13:09

    Other alternative if you're using Pydev that also works in a multithreading is:

    try:
        import pydevd
        DEBUGGING = True
    except ImportError:
        DEBUGGING = False
    
    0 讨论(0)
提交回复
热议问题