检查程序是否在PyCharm 2023中以JavaScript模式运行

fjnneemd  于 5个月前  发布在  PyCharm
关注(0)|答案(2)|浏览(73)

我使用PyCharm IDE进行Python编程。我以前使用Check if program runs in Debug mode中描述的方法来检查运行程序时是否处于调试模式。
然而,在PyCharm的2023.3更新之后,这些方法停止工作。例如,

sys.gettrace() is None

字符串
无论是否为调试模式,计算结果都为True

uqxowvwt

uqxowvwt1#

我想我已经找到了一个新的解决方案,它建立在awesoon的this answer之上。
根据文档,可以使用settrace/gettrace函数 * 或 * breakpointhook * 函数 * 来实现Python调试器:

sys.settrace(tracefunc)

字符串
设置系统的trace函数,该函数允许您在Python中实现Python源代码调试器。该函数是线程特定的;对于支持多线程的调试器,必须为每个正在调试的线程使用settrace()注册该函数。

sys.breakpointhook()


这个钩子函数由内置的breakpoint()调用。默认情况下,它会将您放入PDB调试器,但它可以设置为任何其他函数,以便您可以选择使用哪个调试器。
您可以使用以下代码段来检查是否有人正在调试您的代码:

import sys
has_trace = hasattr(sys, 'gettrace') and sys.gettrace() is not None
has_breakpoint = sys.breakpointhook.__module__ != "sys"
is_debug = has_trace or has_breakpoint
print(f"{has_trace=} {has_breakpoint=} {is_debug=}")


这一个适用于PDB:

PS C:\Users\pvillano> python -m pdb main.py
> c:\users\pvillano\main.py(1)<module>()
-> import sys
(Pdb) step
> c:\users\pvillano\main.py(2)<module>()
-> has_trace = hasattr(sys, 'gettrace') and sys.gettrace() is not None
(Pdb) step
> c:\users\pvillano\main.py(3)<module>()
-> has_breakpoint = sys.breakpointhook.__module__ != "sys"
(Pdb) step
> c:\users\pvillano\main.py(4)<module>()
-> is_debug = has_trace or has_breakpoint
(Pdb) step
> c:\users\pvillano\main.py(5)<module>()
-> print(f"{has_trace=} {has_breakpoint=} {is_debug=}")
(Pdb) step
has_trace=True has_breakpoint=False is_debug=True
--Return--
> c:\users\pvillano\main.py(5)<module>()->None
-> print(f"{has_trace=} {has_breakpoint=} {is_debug=}")


现在它适用于PyCharm:

C:\Users\pvillano\AppData\Local\pypoetry\Cache\virtualenvs\...\Scripts\python.exe -X pycache_prefix=C:\Users\pvillano\AppData\Local\JetBrains\PyCharm2023.3\cpython-cache "C:/Users/python/AppData/Local/Programs/PyCharm Professional/plugins/python/helpers/pydev/pydevd.py" --multiprocess --qt-support=auto --client 127.0.0.1 --port 50772 --file C:\Users\pvillano\main.py 
Connected to pydev debugger (build 233.11799.259)
has_trace=False has_breakpoint=True is_debug=True

Process finished with exit code 0


它也适用于Visual Studio Code

PS C:\Users\pvillano>  c:; cd 'c:\Users\pvillano'; & 'C:\Program Files\Python312\python.exe' 'c:\Users\pvillano\.vscode-oss\extensions\ms-python.python-2023.20.0-universal\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher' '51165' '--' 'C:\Users\pvillano\main.py'
has_trace=True has_breakpoint=True is_debug=True

mfpqipee

mfpqipee2#

它不仅是PyCharm 2023.3,而且是Python 3.12sys.monitoring模块实现的PEP 669 – Low Impact Monitoring for CPython
我建议使用这个新模块的以下解决方案:

import sys

def debug_enabled():

    try:
        if sys.gettrace() is not None:
            return True
    except AttributeError:
        pass

    try:
        if sys.monitoring.get_tool(sys.monitoring.DEBUGGER_ID) is not None:
            return True
    except AttributeError:
        pass

    return False

字符串

相关问题