【问题标题】:Python: How to detect debug interpreterPython:如何检测调试解释器
【发布时间】:2010-10-13 09:20:50
【问题描述】:

如何在我的 python 脚本中检测它是否由调试解释器(即 python_d.exe 而不是 python.exe)运行?我需要更改传递给扩展的一些 dll 的路径。

例如,我想在我的 python 脚本开始时做这样的事情:

#get paths to graphics dlls
if debug_build:
    d3d9Path   = "bin\\debug\\direct3d9.dll"
    d3d10Path  = "bin\\debug\\direct3d10.dll"
    openGLPath = "bin\\debug\\openGL2.dll"
else:
    d3d9Path   = "bin\\direct3d9.dll"
    d3d10Path  = "bin\\direct3d10.dll"
    openGLPath = "bin\\openGL2.dll"

我曾考虑向扩展添加一个“IsDebug()”方法,如果它是调试版本(即使用“#define DEBUG”构建),则返回 true,否则返回 false。但这似乎有点像我确信我可以让 python 告诉我......

【问题讨论】:

  • 您是否考虑过使用原始字符串来避免过度转义? r'bin\debug\direct3d9.dll'

标签: python debugging


【解决方案1】:

Distutils use sys.gettotalrefcount to detect a debug python build:

# ...
if hasattr(sys, 'gettotalrefcount'):
   plat_specifier += '-pydebug'
  • 此方法不依赖于可执行文件名称“*_d.exe”。它适用于任何名称。
  • 此方法是跨平台的。它不依赖于“_d.pyd”后缀。

Debugging BuildsMisc/SpecialBuilds.txt

【讨论】:

  • 这是一个旧答案,但我是来自未来的人,在这里确认这在 Python 3.7.1 上仍然可以正常工作。
  • 这是一个单行示例:python -c "import sys; sys.exit(int(hasattr(sys, 'gettotalrefcount')))" # returns 0 if is a non-debug build, 1 if is a debug build 这是一个 bash 测试:if [[ python -c "import sys; sys.exit(int(hasattr(sys, 'gettotalrefcount')))" ]]; then PYTHON_DEBUG= ; else: PYTHON_DEBUG="y" fi
  • 抱歉删除 bash 示例中的方括号以使其正常工作
【解决方案2】:

更好,因为它也可以在运行嵌入式 Python 解释器时检查返回值

imp.get_suffixes()

对于调试版本,它包含一个以“_d.pyd”开头的元组:

# debug build:
[('_d.pyd', 'rb', 3), ('.py', 'U', 1), ('.pyw', 'U', 1), ('.pyc', 'rb', 2)]

# release build:
[('.pyd', 'rb', 3), ('.py', 'U', 1), ('.pyw', 'U', 1), ('.pyc', 'rb', 2)]

【讨论】:

    【解决方案3】:

    一个简单的方法,如果你不介意依赖文件名:

    if sys.executable.endswith("_d.exe"):
      print "running on debug interpreter"
    

    您可以阅读有关sys 模块及其各种设施here 的更多信息。

    【讨论】:

      猜你喜欢
      • 2011-12-03
      • 2012-05-04
      • 1970-01-01
      • 1970-01-01
      • 2012-04-11
      • 2011-10-11
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多