Sometimes I only want print statements to execute if I’m debugging a program, and I don’t want them to execute for the user. Here’s how to tell if you are in debug mode.
import sys
has_trace = hasattr(sys, 'gettrace') and sys.gettrace() is not None
has_breakpoint = sys.breakpointhook.__module__ != "sys"
isdebug = has_trace or has_breakpoint
print(f"{has_trace=} {has_breakpoint=} {isdebug=}")
I put this right at the beginning of my program after any import statements.
Changing the behavior of your program when inside a debugger seems like a recipe for great frustration.
I would recommend using the logging module instead. Then you can set the level at which specific messages are shown (e.g. debug, info, warning, error).
@pytest.mark.skipif(
(not hasattr(sys, "gettrace") or sys.gettrace() is None)
and sys.breakpointhook.__module__ == "sys",
reason="only for debugging",
)
def test_run_server():
server()
Im testing server+client where the server is running in a separate process.
So Process(target=server). Sometimes I am unsure if it’s the client or the server that is currently broken so I just want to debug the server and use an external client to send commands. But the server function doesn’t terminate by itself so I only want it to run if I’m specifically debugging the server.