### Complete Debug Setup Example Source: https://context7.com/microsoft/debugpy/llms.txt A full implementation example showing programmatic debugpy integration within a Flask application. ```python # app.py - Flask application with debugpy integration import os import debugpy def setup_debugging(): """Configure debugpy for development debugging.""" if os.environ.get("ENABLE_DEBUGPY"): # Enable logging for troubleshooting log_dir = os.environ.get("DEBUGPY_LOG_DIR") if log_dir: debugpy.log_to(log_dir) # Configure subprocess handling debugpy.configure(subProcess=False) # Start debug server port = int(os.environ.get("DEBUGPY_PORT", 5678)) host, actual_port = debugpy.listen(("0.0.0.0", port)) print(f"debugpy listening on {host}:{actual_port}") # Optionally wait for client if os.environ.get("DEBUGPY_WAIT"): print("Waiting for debugger to attach...") debugpy.wait_for_client() print("Debugger attached!") # Call before app initialization setup_debugging() from flask import Flask app = Flask(__name__) @app.route("/") def index(): debugpy.breakpoint() # Programmatic breakpoint return "Hello, World!" if __name__ == "__main__": app.run(host="0.0.0.0", port=8000) ``` ```bash # Run with debugging enabled ENABLE_DEBUGPY=1 DEBUGPY_WAIT=1 python app.py ``` -------------------------------- ### Start Debug Server and Listen for Connections Source: https://github.com/microsoft/debugpy/wiki/API-Reference Import debugpy and start the debug server to listen for incoming DAP client connections on a specified port. The script continues execution after starting the listener. ```python import debugpy debugpy.listen(5678) # listen for incoming DAP client connections on 127.0.0.1:5678 print('Hello World') ``` -------------------------------- ### Install debugpy Source: https://context7.com/microsoft/debugpy/llms.txt Install debugpy using pip. ```bash pip install debugpy ``` -------------------------------- ### Start debugpy via CLI Source: https://github.com/microsoft/debugpy/wiki/DAP-Client-reference Command to initiate the debug adapter using stdin/stdout for communication. ```console python ~/debugpy/adapter ``` -------------------------------- ### debugpy.listen() - Start Debug Server Source: https://context7.com/microsoft/debugpy/llms.txt Starts a debug adapter that listens for incoming DAP client connections. Can specify host, port, or let the system pick an available port. ```python import debugpy # Listen on localhost port 5678 debugpy.listen(5678) # Listen with explicit host and port tuple debugpy.listen(("localhost", 5678)) # Listen on all interfaces for remote debugging debugpy.listen(("0.0.0.0", 5678)) # Let the system pick an available port host, port = debugpy.listen(0) print(f"Debug server listening on {host}:{port}") # Use in-process adapter (disables automatic subprocess debugging) debugpy.listen(5678, in_process_debug_adapter=True) ``` -------------------------------- ### Start Debug Server and Wait for Client Attachment Source: https://github.com/microsoft/debugpy/wiki/API-Reference Import debugpy, start the debug server, and then block script execution until a DAP client attaches. This ensures breakpoints can be set and hit before the script proceeds. ```python import debugpy debugpy.listen(("localhost", 5678)) # listen for incoming DAP client connections debugpy.wait_for_client() # wait for a client to connect print('Hello World') ``` -------------------------------- ### Example test log path Source: https://github.com/microsoft/debugpy/blob/main/CONTRIBUTING.md Sample output showing the location of a test failure log file. ```text Log on failure: -------------------- C:\Users\rchiodo\AppData\Local\Temp\pytest-of-rchiodo\pytest-77\popen-gw3\test_path_translation_and_sour0\pydevd_debug_file_23524.32540.txt ------------------ ``` -------------------------------- ### Install development tools Source: https://github.com/microsoft/debugpy/blob/main/CONTRIBUTING.md Install required Python packages for development using pip. ```bash py -m pip install black flake8 tox ``` ```bash python3 -m pip install black flake8 tox ``` -------------------------------- ### Basic C 'Hello World' for WebAssembly Source: https://github.com/microsoft/debugpy/wiki/Debugpy-with-Webassembly-(proposal) A standard C program that prints 'Hello World'. This serves as a basic example to illustrate the compilation process to WebAssembly. ```c #include int main() { printf("Hello World\n"); return 0; } ``` -------------------------------- ### Example Log Output for Breakpoint Command Source: https://github.com/microsoft/debugpy/blob/main/CONTRIBUTING.md This snippet shows an example of log output for a 'CMD_SET_BREAK' command received by the debugger. It includes timestamps and details about the breakpoint being set, such as line number and file path. ```text 0.00s - Received command: CMD_SET_BREAK 111 3 1 python-line C:\Users\rchiodo\source\repos\PyDev.Debugger\tests_python\resources\_debugger_case_remove_breakpoint.py 7 None None None ``` -------------------------------- ### Enable Debugging via Import (Listen) Source: https://github.com/microsoft/debugpy/blob/main/README.md Import the debugpy library and call `debugpy.listen()` to start the debug adapter. Specify the host and port as a tuple. ```python import debugpy debugpy.listen(("localhost", 5678)) ``` -------------------------------- ### Retrieve CLI options Source: https://context7.com/microsoft/debugpy/llms.txt Access the configuration options provided when starting debugpy via the command line. ```python import debugpy # When started via: python -m debugpy --listen 5678 --wait-for-client myscript.py options = debugpy.get_cli_options() if options: print(f"Mode: {options.mode}") # "listen" or "connect" print(f"Address: {options.address}") # ("127.0.0.1", 5678) print(f"Target kind: {options.target_kind}") # "file", "module", "code", or "pid" print(f"Target: {options.target}") # "myscript.py" print(f"Wait for client: {options.wait_for_client}") # True print(f"Config: {options.config}") # {"subProcess": True, ...} else: print("debugpy was not started via CLI") ``` -------------------------------- ### Enable Logging in launch.json Source: https://github.com/microsoft/debugpy/wiki/Enable-debugger-logs Set logToFile to true within a launch configuration to enable debugger logs. Logs are stored in the extension installation directory. ```json5 { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal", "logToFile": true, } ``` -------------------------------- ### Example test failure output Source: https://github.com/microsoft/debugpy/blob/main/CONTRIBUTING.md Sample output showing failed test cases and summary statistics. ```text =============================================== short test summary info =============================================== FAILED tests_python/test_debugger.py::test_path_translation[True] - AssertionError: TimeoutError (note: error trying to dump threads on timeout). FAILED tests_python/test_debugger.py::test_remote_debugger_multi_proc[False] - AssertionError: TimeoutError FAILED tests_python/test_debugger.py::test_path_translation[False] - AssertionError: TimeoutError (note: error trying to dump threads on timeout). ======================== 3 failed, 661 passed, 169 skipped, 77 warnings in 319.05s (0:05:19) ========================= ``` -------------------------------- ### Run script with debugpy CLI Source: https://github.com/microsoft/debugpy/wiki/Switching-over-from-`ptvsd`-to-`debugpy` Example of how to run a Python script with debugpy using command-line arguments, specifying the listen address and port, and wait-for-client behavior. ```bash > python debugpy --listen localhost:5678 --wait-for-client ./myscript.py ``` -------------------------------- ### Example: Using Breakpoints Source: https://github.com/microsoft/debugpy/wiki/API-Reference Illustrates setting multiple breakpoints within a function. The debugger stops at each `debugpy.breakpoint()` call when a client is connected. ```python import debugpy def foo(): debugpy.breakpoint() print('here') # Debugger stops here debugpy.breakpoint() # Debugger won't stop since there is no next line in this block foo() ``` -------------------------------- ### Start debugpy server on remote machine Source: https://github.com/microsoft/debugpy/wiki/Debugging-over-SSH Launches the debugpy server on the remote host, listening on the specified port and waiting for a client connection. ```bash user1@remote1:~/project1$ python3 -m debugpy --listen 5678 --wait-for-client ./myscript.py ``` -------------------------------- ### Launching a Program in Debug Session Source: https://github.com/microsoft/debugpy/blob/main/tests/timeline.md Use the `debug_session.launch()` context manager to start a debugpy process and connect to it. The timeline is live and records the initial handshake sequence. ```python with debug_session.launch(targets.Program('example.py')): ... ``` -------------------------------- ### Local Debugging Configuration Source: https://github.com/microsoft/debugpy/wiki/Command-Line-Reference Command to start the debugger locally and the corresponding VS Code attach configuration. ```bash debugpy --listen 5678 ./myscript.py ``` ```json5 { "name": "Attach", "type": "python", "request": "attach", "connect": { "port": 5678, } } ``` -------------------------------- ### Example: Conditional Thread Tracing Source: https://github.com/microsoft/debugpy/wiki/API-Reference Shows how to enable tracing before a performance-intensive operation and disable it afterward to optimize execution speed. ```python import debugpy def foo(): debugpy.trace_this_thread(True) # Some performance intensive operation. debugpy.trace_this_thread(False) foo() ``` -------------------------------- ### Example: Configure Subprocess Handling Source: https://github.com/microsoft/debugpy/wiki/API-Reference Configures the debug server not to automatically inject itself into subprocesses, which is useful for 'attach' scenarios. This must be called before `connect()` or `listen()`. ```json5 debugpy.configure(subProcess=False) debugpy.listen(...) ``` -------------------------------- ### Install GDB in Dockerfile Source: https://github.com/microsoft/debugpy/wiki/Debugging-inside-of-a-docker-container Include these commands in your Dockerfile to ensure the GDB debugger is available for attachment. ```dockerfile RUN apt-get update && \ apt-get install -y gdb && \ apt-get clean ``` -------------------------------- ### Calling an Exported Function from a WebAssembly Instance Source: https://github.com/microsoft/debugpy/wiki/Debugpy-with-Webassembly-(proposal) Example of how to call an exported function, such as 'main', from a WebAssembly instance using JavaScript. ```javascript instance.export.main(); ``` -------------------------------- ### debugpy.get_cli_options() Source: https://context7.com/microsoft/debugpy/llms.txt Retrieve the CLI options that were passed when debugpy was started from the command line. Returns a `CliOptions` dataclass or `None`. ```APIDOC ## debugpy.get_cli_options() ### Description Retrieve the CLI options that were passed when debugpy was started from the command line. Returns a `CliOptions` dataclass with all processed options, or `None` if the CLI entry point was not used. ### Method `debugpy.get_cli_options()` ### Response #### Success Response (200) - **CliOptions** (dataclass) - Contains parsed CLI options like mode, address, target, etc. ### Response Example ```python import debugpy # When started via: python -m debugpy --listen 5678 --wait-for-client myscript.py options = debugpy.get_cli_options() if options: print(f"Mode: {options.mode}") # "listen" or "connect" print(f"Address: {options.address}") # ("127.0.0.1", 5678) print(f"Target kind: {options.target_kind}") # "file", "module", "code", or "pid" print(f"Target: {options.target}") # "myscript.py" print(f"Wait for client: {options.wait_for_client}") # True print(f"Config: {options.config}") # {"subProcess": True, ...} else: print("debugpy was not started via CLI") ``` ``` -------------------------------- ### Run Python Script with Debugger Source: https://github.com/microsoft/debugpy/blob/main/README.md Execute a Python script with debugging enabled, listening on a specified host and port. The script starts immediately. ```console -m debugpy --listen localhost:5678 myfile.py ``` -------------------------------- ### Run script with ptvsd CLI Source: https://github.com/microsoft/debugpy/wiki/Switching-over-from-`ptvsd`-to-`debugpy` Example of how to run a Python script with ptvsd using command-line arguments, specifying host, port, and wait behavior. ```bash > python ptvsd --host localhost --port 5678 --wait ./myscript.py ``` -------------------------------- ### Remote Debugging with pydevd Source: https://github.com/microsoft/debugpy/blob/main/src/debugpy/_vendored/pydevd/README.md Use this to initiate a remote debugging session. Ensure pydevd is installed in the remote environment. ```python import pydevd pydevd.settrace(host="10.1.1.1") ``` ```python import pydevd pydevd.settrace(host="10.1.1.1", protocol="dap") ``` -------------------------------- ### Run Python Script and Wait for Client Source: https://github.com/microsoft/debugpy/blob/main/README.md Execute a Python script with debugging enabled, waiting for a client to attach before starting execution. This is useful for debugging startup code. ```console -m debugpy --listen localhost:5678 --wait-for-client myfile.py ``` -------------------------------- ### Example: Debugging a Custom Thread Source: https://github.com/microsoft/debugpy/wiki/API-Reference Demonstrates how to use `debug_this_thread()` on a custom thread created using `ctypes` to ensure breakpoints are active. ```python import debugpy def foo(x): debugpy.debug_this_thread() print('set breakpoint here') return 0 from ctypes import CFUNCTYPE, c_void_p, c_size_t, c_uint32, windll event = threading.Event() thread_func_p = CFUNCTYPE(c_uint32, c_void_p) thread_func = thread_func_p(foo) assert windll.kernel32.CreateThread(c_void_p(0), c_size_t(0), thread_func, c_void_p(0), c_uint32(0), c_void_p(0)) event.wait() ``` -------------------------------- ### Remote Debugging Configuration Source: https://github.com/microsoft/debugpy/wiki/Command-Line-Reference Command to start the debugger on a remote host and the corresponding VS Code attach configuration. ```bash debugpy --listen 0.0.0.0:5678 ./myscript.py ``` ```json5 { "name": "Attach", "type": "python", "request": "attach", "connect": { "host": "remote-machine-name", // replace this with remote machine name "port": 5678, } } ``` -------------------------------- ### Update bytecode dependency from master branch Source: https://github.com/microsoft/debugpy/blob/main/src/debugpy/_vendored/pydevd/_pydevd_frame_eval/vendored/README.txt Use this command to install the latest version of the bytecode library directly from the GitHub repository master branch. ```bash python -m pip install https://github.com/MatthieuDartiailh/bytecode/archive/main.zip --target . ``` -------------------------------- ### Generate New Version and Build Source: https://github.com/microsoft/debugpy/blob/main/src/debugpy/_vendored/pydevd/build_tools/pydevd_release_process.txt Commands to build the project and upload to PyPi. ```bash cd /D x:\debugpyws\PyDev.Debugger set FORCE_PYDEVD_VC_VARS=C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvars64.bat set PYTHONPATH=x:\debugpyws\PyDev.Debugger set MINICONDA_ENVS=D:\bin\miniconda\envs python build_tools\build.py python build_tools\build_binaries_windows.py rm dist/pydevd* deactivate activate py38_64 python setup.py sdist bdist_wheel deactivate dir dist activate py39_64 python setup.py sdist bdist_wheel deactivate dir dist activate py310_64 python setup.py sdist bdist_wheel deactivate dir dist activate py311_64 python setup.py sdist bdist_wheel deactivate dir dist twine upload dist/pydevd* --repository pydevd git tag pydev_debugger_2_9_5 -a -m "PyDev.Debugger 2.9.5" git push --tags ``` -------------------------------- ### Enable Debugging via Import (Listen on Default Host) Source: https://github.com/microsoft/debugpy/blob/main/README.md Import the debugpy library and call `debugpy.listen()` with only a port number. This defaults the host to '127.0.0.1'. ```python import debugpy debugpy.listen(5678) ``` -------------------------------- ### debug_this_thread() Source: https://github.com/microsoft/debugpy/wiki/API-Reference Makes the debugger aware of the current thread and starts tracing it. Essential for breakpoints in non-standard threads. ```APIDOC ## `debug_this_thread()` ### Description Makes the debugger aware of the current thread, and start tracing it. Must be called on any background thread that is started by means other than the usual Python APIs (i.e. the `threading` module), in order for breakpoints to work on that thread. ### Usage ```py debugpy.debug_this_thread() ``` ### Example ```py import debugpy import threading def foo(x): debugpy.debug_this_thread() print('set breakpoint here') return 0 from ctypes import CFUNCTYPE, c_void_p, c_size_t, c_uint32, windll event = threading.Event() thread_func_p = CFUNCTYPE(c_uint32, c_void_p) thread_func = thread_func_p(foo) assert windll.kernel32.CreateThread(c_void_p(0), c_size_t(0), thread_func, c_void_p(0), c_uint32(0), c_void_p(0)) event.wait() ``` ``` -------------------------------- ### Add DLL Binaries to Git Source: https://github.com/microsoft/debugpy/blob/main/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/README.txt Stage dynamic-link library files for version control. ```bash git add *.dll ``` -------------------------------- ### Launch Configuration with Program Path Source: https://github.com/microsoft/debugpy/wiki/Debug-configuration-settings Use the 'program' property to specify the absolute path to the Python script you want to debug. Ensure the path is correct for your system. ```json { "name": "Launch Program", "type": "python", "request": "launch", "program": "/path/to/your/script.py" } ``` -------------------------------- ### Run code formatting with Black Source: https://github.com/microsoft/debugpy/blob/main/CONTRIBUTING.md Reformat code files using Black. ```bash py -m black ``` ```bash python3 -m black ``` -------------------------------- ### Ignore Subprocesses Source: https://github.com/microsoft/debugpy/blob/main/README.md Configure the debugger to ignore subprocesses started by the debugged process. This can be combined with attaching to a process by PID. ```console -m debugpy --listen localhost:5678 --pid 12345 --configure-subProcess False ``` -------------------------------- ### debugpy.listen() Source: https://github.com/microsoft/debugpy/wiki/API-Reference Sets up the debug server to listen for incoming DAP client connections. ```APIDOC ## listen(address, *, in_process_debug_adapter: bool = False) ### Description Tells the debug server to listen for incoming DAP client connections on the specified network interface and port. ### Parameters - **address** (tuple or int) - Required - Must be a (host, port) tuple or a port number. If port is 0, an ephemeral port is picked. - **in_process_debug_adapter** (bool) - Optional - If True, does not spawn a separate process for the debug adapter. ### Response - **(host, port)** (tuple) - Returns the actual interface and port on which the debug server is listening. ### Request Example ```python debugpy.listen(5678) debugpy.listen(('localhost', 5678)) ``` ``` -------------------------------- ### Docker Container Debugging Source: https://context7.com/microsoft/debugpy/llms.txt Setup for debugging Python applications inside Docker containers using port mapping. ```dockerfile # Dockerfile FROM python:3.11 RUN pip install debugpy COPY . /app WORKDIR /app # Expose debug port EXPOSE 5678 CMD ["python", "-m", "debugpy", "--listen", "0.0.0.0:5678", "--wait-for-client", "app.py"] ``` ```bash # Run container with port mapping docker run -p 5678:5678 myapp ``` ```json { "name": "Attach (Docker)", "type": "python", "request": "attach", "connect": { "host": "localhost", "port": 5678 }, "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/app" } ] } ``` -------------------------------- ### Update bytecode dependency via pip Source: https://github.com/microsoft/debugpy/blob/main/src/debugpy/_vendored/pydevd/_pydevd_frame_eval/vendored/README.txt Use this command to install the latest version of the bytecode library into the current directory. ```bash pip install bytecode --target . ``` -------------------------------- ### Launch Configuration with Script Arguments Source: https://github.com/microsoft/debugpy/wiki/Debug-configuration-settings Pass command-line arguments to your Python script using the 'args' property. This is essential for scripts that expect input parameters. ```json { "name": "Launch with Script Args", "type": "python", "request": "launch", "program": "${file}", "args": ["--arg1", "-arg2", "val"] } ``` -------------------------------- ### Extract Debugger Binaries (macOS) Source: https://github.com/microsoft/debugpy/blob/main/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/README.txt Command to extract macOS debugger binaries using 7-Zip. Ensure 7-Zip is installed and in your PATH. ```bash "C:\Program Files\7-Zip\7z" e C:\Users\fabio\Downloads\mac_binaries.zip -oX:\PyDev.Debugger\pydevd_attach_to_process * -r -y ``` -------------------------------- ### Extract Debugger Binaries (Linux) Source: https://github.com/microsoft/debugpy/blob/main/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/README.txt Command to extract Linux debugger binaries using 7-Zip. Ensure 7-Zip is installed and in your PATH. ```bash "C:\Program Files\7-Zip\7z" e C:\Users\fabio\Downloads\linux_binaries.zip -oX:\PyDev.Debugger\pydevd_attach_to_process * -r -y ``` -------------------------------- ### Extract Debugger Binaries (Windows) Source: https://github.com/microsoft/debugpy/blob/main/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/README.txt Command to extract Windows debugger binaries using 7-Zip. Ensure 7-Zip is installed and in your PATH. ```bash "C:\Program Files\7-Zip\7z" e C:\Users\fabio\Downloads\win_binaries.zip -oX:\PyDev.Debugger\pydevd_attach_to_process * -r -y ``` -------------------------------- ### Configuring Debug Session and Setting Breakpoints Source: https://github.com/microsoft/debugpy/blob/main/tests/timeline.md Within the `launch` context, configure session settings like 'redirectOutput' and issue requests to set breakpoints at specific lines in the target program. ```python with debug_session.launch(targets.Program('example.py')): debug_session.config['redirectOutput]' = True debug_session.request('setBreakpoints', [ { 'source': {'path': 'example.py'}, 'breakpoints': [{'line': 3}, {'line': 5}] } ]) ``` -------------------------------- ### Add Executable Binaries to Git Source: https://github.com/microsoft/debugpy/blob/main/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/README.txt Stage executable files for version control. ```bash git add *.exe ``` -------------------------------- ### Launch Configuration with Code Execution Source: https://github.com/microsoft/debugpy/wiki/Debug-configuration-settings The 'code' property allows you to execute arbitrary Python code directly. This is useful for quick tests or debugging specific lines without a full script. ```json { "name": "Execute Code", "type": "python", "request": "launch", "code": "import debugpy;print(debugpy.__version__)" } ``` -------------------------------- ### Set Log Directory Source: https://github.com/microsoft/debugpy/wiki/API-Reference Specifies a directory for `debugpy` to write detailed logs. Log files are generated per process and start with `debugpy.`. ```python debugpy.log_to("/tmp/logs") ``` -------------------------------- ### Launch/Attach Configuration Settings Source: https://github.com/microsoft/debugpy/wiki/Debug-configuration-settings Detailed reference for configuration properties used to control code execution and debugger behavior. ```APIDOC ## Launch/Attach Configuration ### Description Settings used in the Launch/Attach Request for DAP clients to configure the debugging environment. ### Request Body - **module** (string) - Launch - Name of the module to be debugged. - **program** (string) - Launch - Absolute path to the program. - **code** (string) - Launch - Code to execute in string form. - **python** (Array[string]) - Launch - Path to python executable and interpreter arguments. - **args** (Array[string]) - Launch - Command line arguments passed to the program. - **console** (Enum) - Launch - Sets where to launch the debug target (internalConsole, integratedTerminal, externalTerminal). - **cwd** (string) - Launch - Absolute path to the working directory. - **env** (Object) - Launch - Environment variables as key-value pairs. - **django** (Boolean) - Launch/Attach - Enables Django templates. - **gevent** (Boolean) - Launch/Attach - Enables debugging of gevent monkey-patched code. - **jinja** (Boolean) - Launch/Attach - Enables Jinja2 template debugging. - **justMyCode** (Boolean) - Launch/Attach - Debug only user-written code. - **logToFile** (Boolean) - Launch/Attach - Enables logging of debugger events. - **pathMappings** (Array[Object]) - Launch/Attach - Map of local and remote paths. - **pyramid** (Boolean) - Launch/Attach - Enables debugging Pyramid applications. - **redirectOutput** (Boolean) - Launch/Attach - Redirects output to debug console. - **showReturnValue** (Boolean) - Launch/Attach - Shows return value of functions when stepping. - **stopOnEntry** (Boolean) - Launch - Stops at first line of user code. - **subProcess** (Boolean) - Launch/Attach - Enables debugging multiprocess applications. - **sudo** (Boolean) - Launch/Attach - Runs program under elevated permissions. ``` -------------------------------- ### configure() Source: https://github.com/microsoft/debugpy/wiki/API-Reference Sets debug properties known before client connection, useful for attach configurations. ```APIDOC ## `configure()` ### Description Sets a debug property that must be known to the debug server before the client connects. Such properties can be used directly in "launch" configurations, because in that case the debuggee process after the configuration is passed. But for "attach" configurations, the process can run for a long time before it receives the debug configuration from an attaching client, and thus a different mechanism must be used to set the property values. Currently, the only property like that is `"subProcess"`. This function must be called before calling `connect()` or `listen()`. ### Usage ```py debugpy.configure({"property": value, ...}) debugpy.configure(property=value, ...) ``` ### Example If you don't want the debug server to automatically inject itself into subprocesses spawned by the process you're attaching to, specify it like so: ```json5 debugpy.configure(subProcess=False) debugpy.listen(...) ``` This is the "attach" equivalent to the following "launch" debug configuration: ```json5 { "subProcess": false } ``` ``` -------------------------------- ### Create Git Tag Source: https://github.com/microsoft/debugpy/blob/main/src/debugpy/_vendored/pydevd/build_tools/pydevd_release_process.txt Commands to create and push a new release tag to the repository. ```bash git tag pydev_debugger_3_4_1 -a -m "PyDev.Debugger 3.4.1" git push origin pydev_debugger_3_4_1 ``` -------------------------------- ### Implement WASI imports for Hello World in JavaScript Source: https://github.com/microsoft/debugpy/wiki/Debugpy-with-Webassembly-(proposal) Provides a basic implementation of WASI imports to handle standard output and memory access for a WASM module. Requires a WASM file named 'hello_world_wasi.wasm' to be present. ```javascript var heapu32; var heapu8; var stdout = console.log.bind(console); var stderr = console.warn.bind(console); var streams = ['', '', '']; function printChar(stream, curr) { var dest = stream === 1 ? stdout : stderr; if (curr === 0 || curr === 10) { var str = streams[stream]; dest(str); streams[stream] = ''; } else { streams[stream] += String.fromCharCode(curr); } } function _fd_write(fd, iov, iovcnt, pnum) { var num = 0; for (var i = 0; i < iovcnt; i++) { var ptr = heapu32[((iov) >> 2)]; var len = heapu32[(((iov) + (4)) >> 2)]; iov += 8; for (var j = 0; j < len; j++) { printChar(fd, heapu8[ptr + j]); } num += len; } heapu32[((pnum) >> 2)] = num; return 0; } function _fd_close(fd) { return 0; } function _fd_fdstat_get(fd, iov) { return 0; } function _fd_seek(fd, offset, where) { return 0; } function _proc_exit() { return 0; } const imports = {}; imports.wasi_snapshot_preview1 = {}; imports.wasi_snapshot_preview1.fd_write = _fd_write; imports.wasi_snapshot_preview1.fd_close = _fd_close; imports.wasi_snapshot_preview1.fd_fdstat_get = _fd_fdstat_get; imports.wasi_snapshot_preview1.fd_seek = _fd_seek; imports.wasi_snapshot_preview1.proc_exit = _proc_exit; fetch("hello_world_wasi.wasm") .then(resp => WebAssembly.instantiateStreaming(resp, imports)) .then(result => { console.log(`Starting wasm`); heapu32 = new Uint32Array(result.instance.exports.memory.buffer); heapu8 = new Uint8Array(result.instance.exports.memory.buffer); result.instance.exports._start(); }) ``` -------------------------------- ### Launch Configuration with Environment Variables Source: https://github.com/microsoft/debugpy/wiki/Debug-configuration-settings Define environment variables for the debugged process using the 'env' property. This allows you to set up specific environmental conditions for your application. ```json { "name": "Launch with Env Vars", "type": "python", "request": "launch", "program": "${file}", "env": { "MY_VAR": "my_value", "ANOTHER_VAR": "another_value" } } ``` -------------------------------- ### Launch Configuration with Module Source: https://github.com/microsoft/debugpy/wiki/Debug-configuration-settings Use the 'module' property to specify the name of the module to be debugged. This is useful for launching Python applications that are structured as modules. ```json { "name": "Launch Program", "type": "python", "request": "launch", "module": "my_module" } ``` -------------------------------- ### Debug Current Thread Source: https://github.com/microsoft/debugpy/wiki/API-Reference Makes the debugger aware of the current thread and starts tracing it. Essential for breakpoints to work on threads not created via the standard `threading` module. ```python debugpy.debug_this_thread() ``` -------------------------------- ### Common debugpy CLI Recipes Source: https://github.com/microsoft/debugpy/wiki/Command-Line-Reference Quick commands for running scripts, modules, or code strings with the debugger. ```bash debugpy --listen 5678 --wait-for-client ./myscript.py ``` ```bash debugpy --listen 5678 --wait-for-client -m mymodule ``` ```bash debugpy --listen 5678 --wait-for-client -c "import sys;print(sys.argv)" ``` -------------------------------- ### Enable Debugger Logging via API Source: https://github.com/microsoft/debugpy/blob/main/README.md Call `debugpy.log_to()` with the desired log directory path before starting the listener. This method is used when integrating debugpy into an application programmatically. ```python debugpy.log_to('path/to/logs') debugpy.listen(...) ``` -------------------------------- ### Run linting with Flake8 Source: https://github.com/microsoft/debugpy/blob/main/CONTRIBUTING.md Execute linting checks from the repository root. ```bash py -m flake8 ``` ```bash python3 -m flake8 ``` -------------------------------- ### debugpy.debug_this_thread() Source: https://context7.com/microsoft/debugpy/llms.txt Make the debugger aware of threads created outside the standard threading module. Call this function on threads started via native APIs to enable breakpoint support. ```APIDOC ## debugpy.debug_this_thread() ### Description Make the debugger aware of threads created outside the standard threading module. Call this function on threads started via native APIs (ctypes, C extensions) to enable breakpoint support on those threads. ### Method `debugpy.debug_this_thread()` ### Request Example ```python import debugpy from ctypes import CFUNCTYPE, c_void_p, c_size_t, c_uint32, windll import threading def native_thread_function(arg): # Register this thread with debugpy debugpy.debug_this_thread() # Now breakpoints will work in this thread print("Processing in native thread") # Set breakpoint here do_work() return 0 # Create thread using Windows API thread_func_type = CFUNCTYPE(c_uint32, c_void_p) thread_func = thread_func_type(native_thread_function) debugpy.listen(5678) debugpy.wait_for_client() windll.kernel32.CreateThread( c_void_p(0), c_size_t(0), thread_func, c_void_p(0), c_uint32(0), c_void_p(0) ) ``` ``` -------------------------------- ### Enable ptrace on host environment Source: https://github.com/microsoft/debugpy/wiki/Debugging-inside-of-a-docker-container Run these commands on the host machine to globally enable ptrace for Docker containers. ```bash echo "kernel.yama.ptrace_scope = 0" | sudo tee /etc/sysctl.d/10-ptrace.conf sudo sysctl --system ``` -------------------------------- ### Send Request and Get Response Body Source: https://github.com/microsoft/debugpy/blob/main/tests/timeline.md The `request()` method provides a convenient way to send a request, wait for its response, and return the response body directly on success. On failure, it raises the appropriate exception. This combines issuing a request and waiting for its result. ```python initialize_response_body = debug_session.request('initialize', {'adapterID': 'test'}) ``` -------------------------------- ### Configure debug properties Source: https://context7.com/microsoft/debugpy/llms.txt Set configuration options like subprocess debugging before the client connects. ```python import debugpy # Disable automatic subprocess debugging debugpy.configure(subProcess=False) debugpy.listen(5678) # Using dict syntax debugpy.configure({"subProcess": False}) debugpy.listen(5678) # Example: Parent process that spawns workers debugpy.configure(subProcess=True) # Debug child processes too debugpy.listen(5678) debugpy.wait_for_client() import subprocess # Child processes will automatically be debugged subprocess.run(["python", "worker.py"]) ``` -------------------------------- ### Listen on Any Interface Source: https://github.com/microsoft/debugpy/blob/main/README.md Configure the debug adapter to listen on all available network interfaces (0.0.0.0) for remote debugging. Use with caution on secure networks. ```console -m debugpy --listen 0.0.0.0:5678 myfile.py ``` -------------------------------- ### Sample Python script for debugging Source: https://github.com/microsoft/debugpy/wiki/Debugging-over-SSH A simple script to test the remote debugging connection. ```py print('hello world') ``` -------------------------------- ### Listen and wait for client in debugpy Source: https://github.com/microsoft/debugpy/wiki/Switching-over-from-`ptvsd`-to-`debugpy` This snippet shows how to configure debugpy to listen on a specific address and port, and then wait for a debugger client to connect. ```python import debugpy debugpy.listen(('localhost', 5678)) debugpy.wait_for_client() ``` -------------------------------- ### VS Code attach configuration Source: https://github.com/microsoft/debugpy/wiki/Debugging-over-SSH JSON configuration for the VS Code launch.json file to connect to the remote debugpy instance. ```js { "name": "Attach", "type": "python", "request": "attach", "connect": { "host": "localhost", "port": 5678 }, "pathMappings": [ { "localRoot": "${workspaceFolder}", // Maps C:\Users\user1\project1 "remoteRoot": "." // To current working directory ~/project1 } ] } ``` -------------------------------- ### Launch Configuration with Python Interpreter Arguments Source: https://github.com/microsoft/debugpy/wiki/Debug-configuration-settings Specify the Python executable path and any interpreter arguments using the 'python' property. This allows customization of the Python environment used for debugging. ```json { "name": "Launch with Args", "type": "python", "request": "launch", "program": "${file}", "python": ["/usr/bin/python", "-E"] } ``` -------------------------------- ### Launch Configuration with Working Directory Source: https://github.com/microsoft/debugpy/wiki/Debug-configuration-settings Set the working directory for the debugged program using the 'cwd' property. This is important for programs that rely on relative paths for file access. ```json { "name": "Launch with CWD", "type": "python", "request": "launch", "program": "${file}", "cwd": "/path/to/working/directory" } ``` -------------------------------- ### Configure devcontainer.json for ptrace Source: https://github.com/microsoft/debugpy/wiki/Debugging-inside-of-a-docker-container Add these run arguments and post-create commands to devcontainer.json to grant the container necessary ptrace capabilities. ```jsonc "runArgs": [ "--cap-add=SYS_PTRACE", "--security-opt=seccomp=unconfined", "--privileged" ], "postCreateCommand": "echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope", ``` -------------------------------- ### Enable Logging via Command Line Arguments Source: https://github.com/microsoft/debugpy/wiki/Enable-debugger-logs Use the --log-to flag when invoking debugpy via the CLI to specify a directory for log storage. ```sh python3 -m debugpy --listen 5678 --wait-for-client --log-to ~/logs myscript.py ``` -------------------------------- ### VS Code Launch Configuration Source: https://context7.com/microsoft/debugpy/llms.txt Standard configuration for launching a Python script directly within VS Code. ```json { "name": "Python: Launch Script", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal", "justMyCode": true, "args": ["--input", "data.json"], "env": { "DEBUG_MODE": "1" }, "cwd": "${workspaceFolder}" } ``` -------------------------------- ### CLI: Enable Logging Source: https://context7.com/microsoft/debugpy/llms.txt Generate detailed debugpy logs for troubleshooting. Logs can be written to a directory or stderr. ```bash python -m debugpy --log-to /path/to/logs --listen 5678 ./myscript.py ``` ```bash python -m debugpy --log-to-stderr --listen 5678 ./myscript.py ``` -------------------------------- ### Debugpy Extension Preamble Source: https://github.com/microsoft/debugpy/blob/main/src/debugpy/_vendored/pydevd/pydevd_plugins/extensions/README.md This preamble is required in `__init__.py` files for both the `pydevd_plugin` and `extension` folders to correctly declare namespace packages for extensions. ```python try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: import pkgutil __path__ = pkgutil.extend_path(__path__, __name__) ``` -------------------------------- ### CLI: Debug a Script File Source: https://context7.com/microsoft/debugpy/llms.txt Run a Python script with debugpy listening for DAP client connections. Use --wait-for-client to pause execution until a client attaches. ```bash python -m debugpy --listen 5678 --wait-for-client ./myscript.py ``` ```bash python -m debugpy --listen localhost:5678 ./myscript.py ``` ```bash python -m debugpy --listen 0.0.0.0:5678 ./myscript.py ``` ```bash python -m debugpy --listen 5678 --wait-for-client ./myscript.py --arg1 value1 --arg2 ``` -------------------------------- ### Run all pydevd tests Source: https://github.com/microsoft/debugpy/blob/main/CONTRIBUTING.md Execute the full test suite in parallel from the root directory. ```bash python -m pytest -n auto -rfE ``` -------------------------------- ### Run a single test case Source: https://github.com/microsoft/debugpy/blob/main/CONTRIBUTING.md Execute a specific test function within a file. ```bash py -m tox --develop -e py312 -- ".\tests\debugpy\server\test_cli.py::test_duplicate_switch" ``` -------------------------------- ### Instantiating a WebAssembly Module in JavaScript Source: https://github.com/microsoft/debugpy/wiki/Debugpy-with-Webassembly-(proposal) JavaScript code to load and instantiate a WebAssembly module. This is the initial step for running Wasm code in a web environment. ```javascript const instance = await WebAssembly.instantiate(wasmModule, imports); ``` -------------------------------- ### debugpy.connect() Source: https://github.com/microsoft/debugpy/wiki/API-Reference Connects the debug server to a DAP client that is waiting for incoming connections. ```APIDOC ## connect(address, access_token, parent_session_pid) ### Description Tells the debug server to connect to a DAP client that is accepting connections on the specified address. ### Parameters - **address** (tuple or int) - Required - Must be a (host, port) tuple or a port number. Defaults to 127.0.0.1 if only port is provided. - **access_token** (string) - Optional - Must match the value passed via the --server-access-token command-line switch. - **parent_session_pid** (int) - Optional - PID of the parent session to associate with. ### Request Example ```python debugpy.connect(5678) debugpy.connect(('localhost', 5678)) ``` ``` -------------------------------- ### Launch configuration for subprocess handling Source: https://github.com/microsoft/debugpy/wiki/Command-Line-Reference This JSON configuration sets the `subProcess` property to `false` within a launch configuration, achieving the same result as the command-line argument for attach configurations. ```json5 { "subProcess": false } ``` -------------------------------- ### Regenerate Cython Files Source: https://github.com/microsoft/debugpy/blob/main/src/debugpy/_vendored/pydevd/build_tools/pydevd_release_process.txt Commands to regenerate .pyx and .c files using the build script. ```bash set FORCE_PYDEVD_VC_VARS=C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvars64.bat cd /D x:\pydev\plugins\org.python.pydev.core\pysrc set PYTHONPATH=x:\pydev\plugins\org.python.pydev.core\pysrc C:\bin\Miniconda\envs\py_38_tests\python.exe build_tools\build.py ``` ```bash "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvars64.bat" cd /D X:\ptvsd_workspace\ptvsd\src\debugpy\_vendored\pydevd set PYTHONPATH=X:\ptvsd_workspace\ptvsd\src\debugpy\_vendored\pydevd C:\bin\Miniconda\envs\py_38_tests\python.exe build_tools\build.py ``` ```bash cd ~/Desktop/Pydev/plugins/org.python.pydev.core/pysrc export PYTHONPATH=~/Desktop/Pydev/plugins/org.python.pydev.core/pysrc python build_tools/build.py ``` -------------------------------- ### Perform a subrepo pull with manual rebase and testing Source: https://github.com/microsoft/debugpy/blob/main/build/git-subrepo/note/pull-dance.txt These sequences allow for testing during the rebase process when pulling subrepo changes. ```bash ( git sr checkout ext/bar --rebase make test git sr pull --continue ) ``` ```bash ( git sr checkout ext/bar git rebase subrepo/remote/ext/bar make test git sr pull --continue ) ``` -------------------------------- ### Run tests with tox Source: https://github.com/microsoft/debugpy/blob/main/CONTRIBUTING.md Execute the test suite in an isolated environment using tox. ```bash py -m tox ``` ```bash python3 -m tox ``` -------------------------------- ### Enable Debugger Logging via CLI Source: https://github.com/microsoft/debugpy/blob/main/README.md Use the `--log-to` switch with the `debugpy` module to direct logs to a specified file path. This is useful for enabling logging when launching a Python script with debugpy. ```console -m debugpy --log-to path/to/logs ... ``` -------------------------------- ### debugpy.connect() - Connect to Client Source: https://context7.com/microsoft/debugpy/llms.txt Connects the debug server to a DAP client that is waiting for incoming connections. Supports explicit host/port, and access tokens for secured connections. ```python import debugpy # Connect to client listening on port 5678 debugpy.connect(5678) # Connect with explicit host and port debugpy.connect(("localhost", 5678)) # Connect with access token for secured connections debugpy.connect(5678, access_token="my-secret-token") # Connect with parent session PID for multi-process debugging debugpy.connect(5678, parent_session_pid=12345) ``` -------------------------------- ### Compile Cython Sources Source: https://github.com/microsoft/debugpy/blob/main/src/debugpy/_vendored/pydevd/README.md Run this script to update and compile Cython sources for speedup modules. The resulting .pyx and .c files should be committed. ```python build_tools/build.py ``` -------------------------------- ### Disable JustMyCode in launch.json Source: https://github.com/microsoft/debugpy/blob/main/TROUBLESHOOTING.md Set justMyCode to false to enable debugging of library files. ```json { "name": "Terminal", "type": "python", "request": "launch", "pythonPath": "${config:python.pythonPath}", "program": "${file}", "console": "integratedTerminal", "justMyCode": false }, ``` -------------------------------- ### Enable debug logging Source: https://context7.com/microsoft/debugpy/llms.txt Direct debugpy logs to a specific directory to troubleshoot connection or breakpoint issues. ```python import debugpy # Enable logging before starting debug server debugpy.log_to("/tmp/debugpy-logs") debugpy.listen(5678) # Logs will be written as debugpy.*.log files # Useful for diagnosing connection or breakpoint issues ``` -------------------------------- ### VS Code launch.json Configuration for Custom Debug Adapter Source: https://github.com/microsoft/debugpy/blob/main/CONTRIBUTING.md Configure Visual Studio Code to use a custom debugpy build by specifying the 'debugAdapterPath' in your launch.json. This path should point to the root directory of the debugpy package within the repository. ```json { "type": "python", "debugAdapterPath": ".../debugpy/src/debugpy/adapter", ... } ``` -------------------------------- ### Sequence Request, Event, and Response Source: https://github.com/microsoft/debugpy/blob/main/tests/timeline.md Asserts a specific sequence: a request, followed by an 'initialized' event, followed by the request's response. This is a common pattern for debugging initialization sequences. ```python initialize = debug_session.send_request('initialize', {'adapterID': 'test'}) initialize_response = initialize_request.wait_for_response() assert ( initialize >> Event('initialized', {}) >> initialize_response ) in debug_session.timeline ``` -------------------------------- ### Configure Subprocess Debugging via API Source: https://github.com/microsoft/debugpy/wiki/FAQ Use the `debugpy.configure` API to enable subprocess debugging when using 'attach' configurations, as the `subProcess` setting in launch.json is not applicable in attach scenarios. ```python import debugpy debugpy.configure(subProcess=True) ``` -------------------------------- ### Listen for DAP Client Connections Source: https://github.com/microsoft/debugpy/wiki/API-Reference Configure the debug server to listen for incoming DAP client connections on a specified network interface and port. The function returns the actual host and port it is listening on. ```python debugpy.listen(5678) ``` ```python debugpy.listen(('localhost', 5678)) ``` ```python debugpy.listen(('0.0.0.0', 5678)) ``` ```python # if you don't want to select the port yourself _, port = debugpy.listen(0) ``` ```python host, port = debugpy.listen(('localhost', 0)) ``` -------------------------------- ### Optimize performance with thread tracing Source: https://context7.com/microsoft/debugpy/llms.txt Toggle tracing on the current thread to improve performance during non-debug sections. ```python import debugpy debugpy.listen(5678) debugpy.wait_for_client() def performance_critical_section(): # Disable tracing for performance debugpy.trace_this_thread(False) # This code runs faster, but breakpoints won't hit for i in range(1000000): heavy_computation(i) # Re-enable tracing for normal debugging debugpy.trace_this_thread(True) # Breakpoints work again here process_results() ``` -------------------------------- ### Run individual pydevd test Source: https://github.com/microsoft/debugpy/blob/main/CONTRIBUTING.md Execute a specific test case by path. ```bash python -m pytest -n auto tests_python/test_debugger.py::test_path_translation[False] ``` -------------------------------- ### Enable Logging via Environment Variable Source: https://github.com/microsoft/debugpy/wiki/Enable-debugger-logs Set the DEBUGPY_LOG_DIR environment variable to a valid directory path to capture debugger logs. ```sh DEBUGPY_LOG_DIR=~/logs ``` -------------------------------- ### debugpy.configure() Source: https://context7.com/microsoft/debugpy/llms.txt Set debug configuration properties before the client connects. Currently supports `subProcess` to control subprocess debugging. ```APIDOC ## debugpy.configure() ### Description Set debug configuration properties before the client connects. Use `configure()` to set properties that must be known early in the debug session, particularly for attach scenarios where the client connects later. Currently supports `subProcess` to control subprocess debugging. ### Method `debugpy.configure(**kwargs)` ### Parameters #### Request Body - **subProcess** (bool) - Optional - Controls whether to automatically debug child processes. ### Request Example ```python import debugpy # Disable automatic subprocess debugging debugpy.configure(subProcess=False) debugpy.listen(5678) # Using dict syntax debugpy.configure({"subProcess": False}) debugpy.listen(5678) # Example: Parent process that spawns workers debugpy.configure(subProcess=True) # Debug child processes too debugpy.listen(5678) debugpy.wait_for_client() import subprocess # Child processes will automatically be debugged subprocess.run(["python", "worker.py"]) ``` ```