如何检测通过调试器正在执行的Python代码? [英] How to detect that Python code is being executed through the debugger?

查看:126
本文介绍了如何检测通过调试器正在执行的Python代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python代码中是否有一种简单的方法来检测该代码是否正在通过Python调试器执行?

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

我有一个使用Java的小型Python应用程序代码(感谢JPype)。在调试Python部分时,我也希望嵌入式JVM也具有调试选项。

I have a small Python application that uses Java code (thanks to JPype). When I'm debugging the Python part, I'd like the embedded JVM to be given debug options too.

推荐答案

一种解决方案使用Python 2.4(应使用2.1之前的任何版本)和Pydev:

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

pdb只需替换 pydevd.py

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.

有用的链接:

  • The Python Debugger
  • The interpreter stack

这篇关于如何检测通过调试器正在执行的Python代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆